在Python中测量套接字到套接字延迟

时间:2013-06-27 14:35:33

标签: python sockets timestamp latency

我使用Python套接字库将消息发送到另一台服务器并测量往返延迟。我只是使用套接字文档(http://wiki.python.org/moin/UdpCommunication)中给出的发送 - 接收示例,因此它非常基础。目前我正在使用time.time()来记录消息何时消失以及何时返回,尽管我希望最终能够获得纳秒精度。现在,我通过我的python脚本获得大约300微秒,但是从shell中ping到大约100微秒。我该怎么做才能更快地进行通信和/或更准确的测量?

发送一条消息的脚本:

import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005
MESSAGE = "Hello, World!"

print "UDP target IP:", UDP_IP
print "UDP target port:", UDP_PORT
print "message:", MESSAGE

sock = socket.socket(socket.AF_INET, # Internet
                       socket.SOCK_DGRAM) # UDP
sock.sendto(MESSAGE, (UDP_IP, UDP_PORT))
print "SENT {0}".format(int(time.time()*1000*1000)

这是侦听ping回来的脚本

import socket

UDP_IP = "originating side localhost ip"
UDP_PORT = 9112
sock = socket.socket(socket.AF_INET, # Internet
                        socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    if data is not None:
        print "received message: {0} {1}".format(data, int(time.time()*1000*1000)

这是在被ping的服务器上侦听的脚本。当它在端口上收到消息时,它会立即发送消息

import socket

UDP_IP = "pinged server's localhost ip"
UDP_PORT = 9111

sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

UDP_IP2 = "ip of server that sent ping"
UDP_PORT2 = 9112
MESSAGE = "HEY"
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

print "Listening on PORT 9111" 

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    if data is not None:
        sock.sendto(MESSAGE, (UDP_IP2, UDP_PORT2))
        print "received message: ", data

0 个答案:

没有答案