问题描述
我想创建一个 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.
Python 2:
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
Python 3:
def timing(f):
def wrap(*args, **kwargs):
time1 = time.time()
ret = f(*args, **kwargs)
time2 = time.time()
print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))
return ret
return wrap
注意我正在调用 f.func_name
以获取字符串形式的函数名称(在 Python 2 中)或 f.__name__
在 Python 3 中.
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时间测量函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!