Python时间测量功能 [英] Python time measure function
问题描述
我想创建一个python函数来测试在每个函数中花费的时间,并打印它的时间,如何打印函数名称,如果有另一种方式,请告诉我
I want to create a python function to test the time spent in each function and print its name with its time, how i can print the function name and if there is another way to do so please tell me
def measureTime(a):
start = time.clock()
a()
elapsed = time.clock()
elapsed = elapsed - start
print "Time spent in (function name) is: ", elapsed
推荐答案
首先,我强烈建议您使用 profiler 或至少使用 timeit 。
First and foremost, I highly suggest using a profiler or atleast use timeit.
然而,如果你想编写自己的计时方法严格地学习,这里是某个地方开始使用装饰器。
However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator.
def timing(f):
def wrap(*args):
time1 = time.time()
ret = f(*args)
time2 = time.time()
print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
return ret
return wrap
,只需使用@timing装饰器:
And the usage is very simple, just use the @timing decorator:
@timing
def do_work():
#code
注意我正在调用 f.func_name
在Python 3中获取函数名作为字符串(在Python 2中)或 f .__ name __
。
Note I'm calling f.func_name
to get the function name as a string(in Python 2), or f.__name__
in Python 3.
这篇关于Python时间测量功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!