通常我们通过网络传送大型字节数据,一般都进行复制、切片、修改等操作,这样操作是非常低效。我们可以通过缓冲区协议对象,实现缓冲区零复制,避免复制、切片等频繁而低效操作。
server.py
import socket
port = 8081
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', 8081))
while True:
data, addr = s.recvfrom(1024)
print "%s bytes from %s" % (len(data), addr)
client1.py
import socket, time
port = 8081
host = "localhost"
bufsize = 1024
## 没有使用缓冲区对象
data = b'a' * 1024 * 1024 * 10
start = time.time()
while data:
sent_bytes = s.sendto(data[:bufsize], (host,port))
data = data[send_bytes]
end = time.time()
print "used_time: %s" % (end -start)
client2.py
import socket, time
port = 8081
host = "localhost"
bufsize = 1024
# memoryview缓冲区协议对象,实现零复制
# memoryview直接引用原内存地址来操作
data =memoryview( b'a' * 1024 * 1024 * 10)
start = time.time()
while data:
sent_bytes = s.sendto(data[:bufsize], (host,port))
data = data[send_bytes]
end = time.time()
print "used_time: %s" % (end -start)