获取 Python 2.7 中代码块的执行时间 [英] Get time of execution of a block of code in Python 2.7

查看:77
本文介绍了获取 Python 2.7 中代码块的执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测量评估 Python 程序中的代码块所用的时间,可能将用户 cpu 时间、系统 cpu 时间和经过时间分开.

I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time.

我知道timeit模块,但是我自己写的函数很多,不是很容易在设置过程中传递它们.

I know the timeit module, but I have many self-written functions and it is not very easy to pass them in the setup process.

我宁愿有一些可以使用的东西:

I would rather have something that could be used like:

#up to here I have done something....
start_counting() #or whatever command used to mark that I want to measure
                   #the time elapsed in the next rows
# code I want to evaluate
user,system,elapsed = stop_counting() #or whatever command says:
                                      #stop the timer and return the times

用户和系统 CPU 时间不是必需的(尽管我想测量它们),但在过去的时间里,我希望能够做这样的事情,而不是使用复杂的命令或模块.

The user and system CPU times are not essential (though I would like to measure them), but for the elapsed time I would like to be able to do something like this, rather than using complicated commands or modules.

推荐答案

要获得以秒为单位的经过时间,您可以使用 timeit.default_timer():

To get the elapsed time in seconds, you can use timeit.default_timer():

import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time

timeit.default_timer() 用于代替 time.time()time.clock() 因为它会选择时间任何平台都具有更高分辨率的功能.

timeit.default_timer() is used instead of time.time() or time.clock() because it will choose the timing function that has the higher resolution for any platform.

这篇关于获取 Python 2.7 中代码块的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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