---
title: "Zero-copy"
author: "huoyanxueren"
date: "2013-02-19T12:26:23Z"
tags: []
categories: ["操作系统"]
slug: "zero-copy"
draft: false
lastmod: "2013-02-21T17:38:06Z"
id: 1807749
url: "https://go-on.iteye.com/blog/1807749"
---

\[译] http://en.wikipedia.org/wiki/Zero-copy

 

"**Zero-copy**" 用来描述主机的CPU不执行将数据从一个存储区复制到另一个的任务。这经常是在网络分发文件的时候用来节省电力和内存。\[1]

 

# **Principle**

各种操作系统上的Zero-copy方式例如设备驱动程序，文件系统，网络协议栈，大大提高了某些应用程序的性能和系统资源利用率。在数据拷贝过到另外一个机器的过程中，允许CPU并行去处理另外的一个任务，性能可以有效地提高。此外， zero-copy 操作减少了用户空间和内核空间的切换时间。让一个cpu去处理大量的数据拷贝，数据拷贝本身是一个简单任务，这是一种极大浪费，如果有其他更简单的系统组件能够代为处理，将能够有效地提高资源利用率。

 

举个例子，读取一个文件，然后通过网络发送。如果文件足够小，并适合放在文件缓存中，传统的方式需要4个数据副本和4个cpu的上下文切换。两个数据拷贝需要用到CPU。如果通过“zero-copy”来发送，cpu上下文切换能减少到2次，CPU的数据拷贝能够减少一半，甚至不用。[\[1\]](http://en.wikipedia.org/wiki/Zero-copy#cite_note-j-zerocopy-1)

 

Zero-copy 对于网络链路的容量接近或者已经超过了CPU的处理能力的高速网络尤其重要。在这种情况下，CPU几乎全花费在了拷贝要传输的数据上，这是个瓶颈，限制了通信的速率只能低于链路容量。行业内的经验，大约一个CPU时钟周期，需要处理一个传入的数据位。

 

附磁盘I/O示例：

![](http://dl.iteye.com/upload/attachment/0080/6968/b79864c5-7118-3e7f-b798-fa7425b7b0c7.jpg)  
 

 

# Implementation

zero-copy 技术需要使用基于[DMA](http://en.wikipedia.org/wiki/Direct_memory_access)的复制和通过[MMU](http://en.wikipedia.org/wiki/Memory_management_unit)的内存映射。这些功能需要特定的硬件支持，通常对于内存也有特定的要求。

 

# Programmatic access

一些操作系统是通过特定的API来支持zero-copy的。

Linux 通过系统调用，比如sys/socket.h 中的sendfile，sendfile64来支持zero-copy。

Windows 通过TransmitFile API来支持zero-copy。

Java input streams 通过 java.nio.channels.FileChannel's transferTo() 方法来支持zero-copy，但是必须是底层操作系统能够支持zero-copy的前提下。[\[1\]](http://en.wikipedia.org/wiki/Zero-copy#cite_note-j-zerocopy-1)

[RDMA](http://en.wikipedia.org/wiki/RDMA) (Remote Direct Memory Access) 协议强依赖于zero-copy技术。

 

# See also

- [Device driver](http://en.wikipedia.org/wiki/Device_driver)
- [Embedded system](http://en.wikipedia.org/wiki/Embedded_system)
- [Infiniband](http://en.wikipedia.org/wiki/Infiniband)
- [Programmed input/output](http://en.wikipedia.org/wiki/Programmed_input/output)
- [Socket Direct Protocol](http://en.wikipedia.org/wiki/Socket_Direct_Protocol)

# References

1、^ [***a***](http://en.wikipedia.org/wiki/Zero-copy#cite_ref-j-zerocopy_1-0) [***b***](http://en.wikipedia.org/wiki/Zero-copy#cite_ref-j-zerocopy_1-1) [***c***](http://en.wikipedia.org/wiki/Zero-copy#cite_ref-j-zerocopy_1-2) [Efficient data transfer through zero copy by Sathish K. Palaniappan and Pramod B. Nagaraja. September 2008](http://www.ibm.com/developerworks/library/j-zerocopy/index.html)