我的任务是定期向服务器发出请求,并将此请求写入数据库。我使用Python 2.7.3,cURL和pycurl作为cURL的包装。我的要求是这样的:Pycurl:如何确定请求的持续时间
import pycurl
c = pycurl.Curl()
c.setopt(c.URL, "http://google.com/")
c.setopt(c.VERBOSE, True) # to see request details
c.perform()
但我怎么能确定这个请求的时间?
UPD1
好的,我明白,我应该服用2个时间戳和它们之间的差异将是请求的持续时间。但我面对一些问题:
当我执行:
import pycurl, time
c = pycurl.Curl()
c.setopt(c.URL, "http://google.com/")
c.setopt(c.VERBOSE, True) # to see request details
ts = time.clock()
c.perform()
print time.clock() - ts
我得到0.0 O(有时)0.01。这是错误的差异,因为我在python shell中执行这个命令,在做ts = time.clock()
之后和我做print time.clock() - ts
之前剩下一些时间,所以差异应该是3秒。
我在我的Ubuntu服务器12.04安装在Virtualbox上的输出。 Virtualbox安装在Windows 7上。当我在Windows 7中尝试下面的代码时,我得到正确的输出。
这是另一个问题 - 也许我应该使用time.time()而不是time.clock()?
解
想法是从this post服用。简单地说,你应该在windows或time.time()上使用time.clock(),在Linux或Unix上(Ubuntu等,FreeBSD和其他,MacOS)。你也可以使用timeit.default_timer()。此函数检测os类型并选择time.time()或time.clock()。因此,该解决方案的代码是:
import pycurl, timeit
c = pycurl.Curl()
c.setopt(c.URL, "http://google.com/")
c.setopt(c.VERBOSE, True) # to see request details
ts = timeit.default_timer()
c.perform()
print timeit.default_timer() - ts
可能的重复[在Python中测量耗用时间](http://stackoverflow.com/questions/7421641/measuring-elapsed-time-in-python) – 2012-08-12 17:04:42
您是否要求_duration_请求,当地时间请求开始,远程服务器收到它的时间,别的......? – 2012-08-12 17:05:46
你在考虑Ping吗? – 2012-08-12 17:07:58