当我从Matlab迁移到python时,我也有同样的问题。在这个线程的帮助下,我能够构造一个Matlabtic()和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)
就这样!现在我们已经准备好充分使用tic()和toc(),就像在Matlab中一样。例如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...
我希望这是有帮助的。