擅长:python、mysql、java
<p>如果您想为函数计时,可以尝试一下装饰器(文档<a href="https://docs.python.org/2/reference/compound_stmts.html#function" rel="nofollow">here</a>):</p>
<pre><code>import time
def timeit(f):
def timed(*args, **kw):
ts = time.time()
result = f(*args, **kw)
te = time.time()
print 'func:%r args:[%r, %r] took: %2.4f sec' % \
(f.__name__, args, kw, te-ts)
return result
return timed
</code></pre>
<p>当你写一个函数时,你只需要使用decorator,这里:</p>
^{pr2}$
<p>这将打印出执行函数所需的时间:</p>
<blockquote>
<p>func:'my_example_function' args:[(), {}] took: 0.4220 sec</p>
</blockquote>