Python定时套接字连接

Mat*_*our 2 python sockets windows network-programming

我希望花时间完成使用TCP的服务器往返.使用Windows客户端时.(我会使用ping,但服务器阻止这个)

我正在寻找使用python和套接字来完成这个,我现在有.

import time
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM )

start = time.time()
s.connect(('localhost',80))
print 'time taken ', time.time()-start ,' seconds'

s.close()
Run Code Online (Sandbox Code Playgroud)

我的问题是我不认为连接计时器正在工作,因为我经常得到相同的时间戳返回.有人能指出我正确的方向来解决这个问题.

Mar*_*ers 5

在Windows上,该time.time()值没有足够的粒度(仅为1/60秒).使用time.perf_counter()它在Windows上有一个微秒的分辨率,而不是约1/3的:

start = time.perf_counter()
s.connect(('localhost',80))
print 'time taken ', time.perf_counter()-start ,' seconds'
Run Code Online (Sandbox Code Playgroud)

这与timeit模块使用的计时器相同; 您可以使用.default_timer()定义:

import timeit

start = timeit.default_timer()
# etc.
Run Code Online (Sandbox Code Playgroud)

这也适用于Python 2,time.perf_counter()它不可用,但 timeit.default_timer()会引用适用于您的操作系统的最佳可用计时器(time.clock()在Windows上,time.time()在其他系统上有大约1/100秒的分辨率).