Python定时套接字连接 [英] Python timing a socket connection

查看:95
本文介绍了Python定时套接字连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am looking to get the time taken to complete a round trip to a server using TCP. When using a windows client. (I would use ping but the server is blocking this)

我正在寻找使用python和套接字来完成此操作,而我目前拥有.

I am looking at using python and sockets to complete this and I currently have.

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()

我遇到的问题是我认为连接计时器不起作用,因为我会定期获得相同的时间戳记.有人可以指出正确的方向来解决这个问题.

The issue I have is I do not think the connection timer is working as I am regularly getting the same time stamp returned. Could someone point me in the right direction to sorting out this issue.

推荐答案

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

On Windows, the time.time() value does not have enough granularity (only 1/60th of a second). Use time.perf_counter() which on Windows has about 1/3rd of a microsecond resolution, instead:

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

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

import timeit

start = timeit.default_timer()
# etc.

这也适用于Python 2,其中time.perf_counter()不可用,但

This also works on Python 2, where time.perf_counter() is not available, but timeit.default_timer() will reference the best-available timer for your OS (time.clock() on Windows, which there has about 1/100th of a second resolution, time.time() on other systems).

这篇关于Python定时套接字连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆