Python速度测试 - 时差 - 毫秒 [英] Python speed testing - Time Difference - milliseconds

查看:159
本文介绍了Python速度测试 - 时差 - 毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中比较2次的正确方式是为了加快测试一段代码?我尝试阅读API文档。我不知道我明白了timedelta的事情。

What is the proper way to compare 2 times in Python in order to speed test a section of code? I tried reading the API docs. I'm not sure I understand the timedelta thing.

到目前为止,我有这个代码:

So far I have this code:

from datetime import datetime

tstart = datetime.now()
print t1

# code to speed test

tend = datetime.now()
print t2
# what am I missing?
# I'd like to print the time diff here


推荐答案

datetime.timedelta 只是两个datetimes之间的区别...所以它就像一段时间,以天/秒/微秒

datetime.timedelta is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a

>>> c
datetime.timedelta(0, 4, 316543)
>>> c.days
0
>>> c.seconds
4
>>> c.microseconds
316543

注意 c.microseconds 只返回timedelta的微秒部分!为了计时,总是使用 c.total_seconds()

Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().

您可以使用datetime.timedelta进行各种数学,例如:

You can do all sorts of maths with datetime.timedelta, eg:

>>> c / 10
datetime.timedelta(0, 0, 431654)

可能更多有用的是看CPU时间而不是wallclock时间,虽然...这是操作系统依赖于...在类Unix系统下,查看'时间'命令。

It might be more useful to look at CPU time instead of wallclock time though ... that's operating system dependant though ... under Unix-like systems, check out the 'time' command.

这篇关于Python速度测试 - 时差 - 毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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