2012-08-12 47 views
0

我的任务是定期向服务器发出请求,并将此请求写入数据库。我使用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 
+1

可能的重复[在Python中测量耗用时间](http://stackoverflow.com/questions/7421641/measuring-elapsed-time-in-python) – 2012-08-12 17:04:42

+0

您是否要求_duration_请求,当地时间请求开始,远程服务器收到它的时间,别的......? – 2012-08-12 17:05:46

+0

你在考虑Ping吗? – 2012-08-12 17:07:58

回答

1
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

thx!但这里有一些问题。我安装了主要的操作系统win7和python 2.7.3。我也有装有python 2.7.3的ubuntu server 12.04的virtualbox。当我在win7上执行time.clock()时,我得到了很好的值,例如14.2348885920,但是当我在虚拟机上执行time.clock()时,我得到的值为0.2,0.4等等(全部<1)。 – dizpers 2012-08-12 17:29:10

+0

如果我使用time.time()就没关系。 – dizpers 2012-08-12 17:29:48

+0

我们应该知道你迄今为止所尝试过的吗?如果你有一个更具体的问题,那么陈述这是你的问题,而不是让我们猜测哪个显然是获得低投票的机会。 – 2012-08-12 17:31:42

0

不使用time.clock()进行计时经过的时间间隔。它现在也被弃用了。