我正在尝试在 google colab 中运行笔记本。我想知道是否有办法让我知道单元是否正在运行以及运行单元需要多长时间(以毫秒为单位)
当您将鼠标悬停在代码块上时,您可以看到一种播放按钮,周围有一个圆形进度环,同时它仍在运行。
要跟踪时间,您可以在执行块的开头添加
%%timeit
,例如
%%timeit
for i in range(1000):
print(i)
# above is a placeholder for your code
它会给你运行代码块所花费的时间(以毫秒为单位)。 或者,您可以执行
%timeit l = [i for i in range(10)] #placeholder for a single line of code
来获取单行的执行时间。
您可以通过计算所花费的时间来检查绝对任何事情的执行时间
import time
t1 = time.perf_counter()
### Your code goes here ###
t2 = time.perf_counter()
print('time taken to run:',t2-t1)
您可以累积跑步所需的时间。一些简单但有用的东西。
示例:
import time
class Timer:
def __init__(self):
self.start = time.perf_counter()
def calcMsUntil(self):
return (time.perf_counter() - self.start) * 1000
# Cell [A]
print('\nCell [A] - start counter')
timer = Timer()
# Cell [B]
print('\nCell [B] - something happens (1 SECOND)')
time.sleep(1)
# Cell [C]
print('\nCell [C]')
print("time until [C]:", timer.calcMsUntil())
# Cell [D]
print('\nCell [D] - something happens (2 SECONDS)')
time.sleep(2)
# Cell [E]
print('\nCell [E]')
print("time until [E]:", timer.calcMsUntil())
结果:
Cell [A] - start counter
Cell [B] - something happens (1 SECOND)
Cell [C]
time until [C]: 1001.7266389995712
Cell [D] - something happens (2 SECONDS)
Cell [E]
time until [E]: 3005.6352470001