在Python中计时代码块而不放入函数中

12 投票
3 回答
3998 浏览
提问于 2025-04-15 19:41

我想要测量一段代码的执行时间,但不想把它放在一个单独的函数里。比如说:

def myfunc:
  # some code here
  t1 = time.time()
  # block of code to time here
  t2 = time.time()
  print "Code took %s seconds." %(str(t2-t1))

不过,我想用timeit模块来更干净地实现这个,但我不想为这段代码单独写一个函数。

谢谢。

3 个回答

0

根据Skilldrick回答,有一个很简单的模块,我觉得可以帮到你:BlockLogginInator

import time
from blocklogginginator import logblock  # logblock is the alias

with logblock(name='one second'):
    """"
    Our code block.
    """
    time.sleep(1)

>>> Block "one second" started 
>>> Block "one second" ended (1.001)
2

你可以通过把想要计时的代码块放在Python的三重引号里面,来设置一个变量来引用这个代码块。然后在创建你的timeit对象时使用这个变量。这个方法有点像我从Python的timeit文档中看到的例子,我想出了以下内容:

import timeit
code_block = """\
total = 0
for cnt in range(0, 1000):
    total += cnt
print total
"""
tmr = timeit.Timer(stmt=code_block)
print tmr.timeit(number=1)

对于我来说,输出是:

499500

0.000341892242432

(这里的499500是被计时代码块的输出,而0.000341892242432是运行所花的时间。)

27

你可以使用with语句来做到这一点。比如说:

import time    
from contextlib import contextmanager

@contextmanager  
def measureTime(title):
    t1 = time.clock()
    yield
    t2 = time.clock()
    print '%s: %0.2f seconds elapsed' % (title, t2-t1)

可以这样使用:

def myFunc():
    #...

    with measureTime('myFunc'):
        #block of code to time here

    #...

撰写回答