TCP与UDP套接字延迟基准

时间:2015-09-18 14:30:33

标签: python sockets tcp udp

我已经在Python中通过TCP和UDP实现了套接字通信的小型基准测试。令人惊讶的是,TCP几乎是UDP的两倍。

为避免路由影响,服务器和客户端在同一台Unix机器上运行,但在不同的线程上运行。

也许代码很有用。这是服务器代码:

import socket
import sys

host = 'localhost'  
port = 8888
buffersize = 8
server_address = (host, port) 

def start_UDP_server():
    socket_UDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socket_UDP.bind(server_address)

    print("UDP server is running...")

    while True:
        data, from_address = socket_UDP.recvfrom(buffersize)
        if not data: break
        socket_UDP.sendto(data, from_address)
    socket_UDP.close()


def start_TCP_server():
    socket_TCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket_TCP.bind(server_address)
    socket_TCP.listen(1)

    print("TCP server is running...")

    while True:    
        client, client_address = socket_TCP.accept()

        while True:
            data = client.recv(buffersize)
            if not data: break
            client.sendall(data)

        client.close()

因此,您可以运行start_TCP_server()start_UDP_server()

在客户端,代码为:

import socket
import sys
import time

host = 'localhost'  
port = 8888
buffersize = 8
server_address = (host, port) 
client_address = (host, port+1)
N = 1000000


def benchmark_UDP():
    socket_UDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
    socket_UDP.bind(client_address)

    print("Benchmark UDP...")

    duration = 0.0
    for i in range(0, N):
        b = bytes("a"*buffersize, "utf-8")
        start = time.time()
        socket_UDP.sendto(b, server_address)
        data, from_address = socket_UDP.recvfrom(buffersize)
        duration += time.time() - start

        if data != b:
            print("Error: Sent and received data are bot the same")

    print(duration*pow(10, 6)/N, "µs for UDP") 


def benchmark_TCP():
    socket_TCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket_TCP.connect(server_address)

    print("Benchmark TCP...")

    duration = 0.0
    for i in range(0, N):
        b = bytes("a"*buffersize, "utf-8")
        start = time.time()
        socket_TCP.sendall(b)
        data = socket_TCP.recv(buffersize)
        duration += time.time() - start

        if data != b:
            print("Error: Sent and received data are bot the same")

    print(duration*pow(10, 6)/N, "µs for TCP")
    socket_TCP.close()

与服务器类似,您可以按benchmark_TCP()benchmark_UDP()启动基准。

对于TCP ,结果约为25μs,对于Unix 约为54μs,对于Windows来说甚至更差(TCP约为30μs,超过200μs)对于UDP)。为什么?我希望UDP具有最小的优势。

1 个答案:

答案 0 :(得分:3)

您的TCP套接字已连接,但您的UDP套接字未连接。这意味着对UDP套接字上的每个发送/接收进行额外处理。在each side上调用connect作为UDP套接字,就像在TCP套接字上调用connect / accept一样。

iperf这样的程序可以做到准确衡量。