matlab tic and toc,什么是Python等价于Matlab的tic和toc函数?

当我从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...

我希望这是有帮助的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值