python - 我想测量代码中 Action 之间传递的时间

标签 python urllib2

我想以毫秒为单位测量时间,这条线花费了:

before=datetime.datetime.now()  
response = urllib2.urlopen("https://www.google.com")
after=datetime.datetime.now()

这应该是服务器的一种变通方法,它不会返回 ping,所以我必须从服务器响应来衡量它。 我可以得到字符串 0:00:00.034225 如果我扣除两次并且我能够将毫秒作为子字符串获取,但我想以更简洁的方式获取毫秒(完全不同毫秒,包括从秒转换而来的时间,如果服务器以非常大的延迟响应)。

最佳答案

after - before 是一个 datetime.timedelta 对象,其 total_seconds 方法将为您提供所需的内容。您可以找到更多信息 in the Python docs .

您只需乘以 1000 即可得到毫秒。别担心,尽管该方法名为 total_seconds,但它包含毫秒作为小数位。示例输出:

>>> d = t1 - t0
>>> d.total_seconds()
2.429001

虽然这不会给您超时,但只会测量持续时间。

关于python - 我想测量代码中 Action 之间传递的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12053883/

相关文章:

python - 为什么在尝试打印时出现 AttributeError

Python urllib2 库

python - 在新线程中加载图像

python urllib2,密码内容和空响应

python - imshow.set_data() 不适用于 FuncAnimation

python - 在 pandas 中过滤、分组和计数?

python - Tkinter:更改函数内的变量

基于组最大值的 Python Dataframe 设置列值

python - 附加到文件无法正常工作

python - 使用 Python 登录 Coursera 帐户