Python中相当于Matlab的tic和toc函数是什么?

158 投票
14 回答
239218 浏览
提问于 2025-04-16 16:46

Python中有什么和Matlab的tic和toc函数相似的功能呢?

14 个回答

25

最简单的理解“tic”和“toc”的方法,就是在Python里直接定义它们。

def tic():
    #Homemade version of matlab tic and toc functions
    import time
    global startTime_for_tictoc
    startTime_for_tictoc = time.time()

def toc():
    import time
    if 'startTime_for_tictoc' in globals():
        print "Elapsed time is " + str(time.time() - startTime_for_tictoc) + " seconds."
    else:
        print "Toc: start time not set"

然后你就可以像这样使用它们:

tic()
# do stuff
toc()
52

我在从Matlab转到Python的时候也有过同样的问题。在这个讨论串的帮助下,我成功地创建了一个和Matlab的tic()toc()函数完全一样的功能。只需要把下面的代码放在你脚本的最上面。

import time

def TicTocGenerator():
    # Generator that returns time differences
    ti = 0           # initial time
    tf = time.time() # final time
    while True:
        ti = tf
        tf = time.time()
        yield tf-ti # returns the time difference

TicToc = TicTocGenerator() # create an instance of the TicTocGen generator

# This will be the main function through which we define both tic() and toc()
def toc(tempBool=True):
    # Prints the time difference yielded by generator instance TicToc
    tempTimeInterval = next(TicToc)
    if tempBool:
        print( "Elapsed time: %f seconds.\n" %tempTimeInterval )

def tic():
    # Records a time in TicToc, marks the beginning of a time interval
    toc(False)

就这样!现在我们可以像在Matlab中那样,完全使用tic()toc()了。例如:

tic()

time.sleep(5)

toc() # returns "Elapsed time: 5.00 seconds."

实际上,这个方法比Matlab内置的函数更灵活。在这里,你可以创建另一个TicTocGenerator的实例,用来跟踪多个操作,或者单独计时。例如,在计时一个脚本的时候,我们现在可以分别计时脚本的每一部分,以及整个脚本的时间。(我会提供一个具体的例子)

TicToc2 = TicTocGenerator() # create another instance of the TicTocGen generator

def toc2(tempBool=True):
    # Prints the time difference yielded by generator instance TicToc2
    tempTimeInterval = next(TicToc2)
    if tempBool:
    print( "Elapsed time 2: %f seconds.\n" %tempTimeInterval )

def tic2():
    # Records a time in TicToc2, marks the beginning of a time interval
    toc2(False)

现在你应该能够计时两个不同的事情:在下面的例子中,我们分别计时整个脚本和脚本的某些部分。

tic()

time.sleep(5)

tic2()

time.sleep(3)

toc2() # returns "Elapsed time 2: 5.00 seconds."

toc() # returns "Elapsed time: 8.00 seconds."

其实,你每次都不需要使用tic()。如果你有一系列想要计时的命令,你可以这样写:

tic()

time.sleep(1)

toc() # returns "Elapsed time: 1.00 seconds."

time.sleep(2)

toc() # returns "Elapsed time: 2.00 seconds."

time.sleep(3)

toc() # returns "Elapsed time: 3.00 seconds."

# and so on...

希望这对你有帮助。

236

除了ThiefMaster提到的timeit,还有一种简单的方法就是(在导入time之后):

t = time.time()
# do stuff
elapsed = time.time() - t

我有一个我喜欢用的辅助类:

class Timer(object):
    def __init__(self, name=None):
        self.name = name

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        if self.name:
            print('[%s]' % self.name,)
        print('Elapsed: %s' % (time.time() - self.tstart))

它可以作为上下文管理器使用:

with Timer('foo_stuff'):
   # do some foo
   # do some stuff

有时候我觉得这个方法比timeit更方便——这完全取决于你想要测量什么。

撰写回答