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

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

问题描述

在 Python 中进行 2 次比较以加快测试一段代码的正确方法是什么?我尝试阅读 API 文档.我不确定我是否理解 timedelta 的事情.

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

from datetime import datetimetstart = datetime.now()打印 t1# 速度测试代码趋势 = datetime.now()打印 t2#我错过了什么?# 我想在这里打印时间差异

解决方案

datetime.timedelta 只是两个日期时间之间的差异......所以它就像一段时间,以天/秒/微秒为单位

<预><代码>>>>导入日期时间>>>a = datetime.datetime.now()>>>b = datetime.datetime.now()>>>c = b - a>>>Cdatetime.timedelta(0, 4, 316543)>>>c.天0>>>c.秒4>>>c.微秒316543

请注意,c.microseconds 仅返回 timedelta 的微秒部分!出于计时目的,请始终使用 c.total_seconds().

你可以用 datetime.timedelta 做各种数学运算,例如:

<预><代码>>>>c/10datetime.timedelta(0, 0, 431654)

查看 CPU 时间而不是挂钟时间可能更有用……尽管这取决于操作系统……在类 Unix 系统下,请查看时间"命令.

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 is just the difference between two datetimes ... so it's like a period of time, in days / seconds / microseconds

>>> import datetime
>>> 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

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

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

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

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天全站免登陆