Reputation: 179
I am trying to run the notebook in Google Colab. I am wondering if there is a way for me to know if the cell is run and how long it took to run the cell (in milliseconds).
Upvotes: 16
Views: 38875
Reputation: 24478
%timeit
is for one-liners. E.g., we can use several in one cell:
%timeit type(5)
%timeit -n 100 -r 3 type(5)
# 73.9 ns ± 19.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
# 90.7 ns ± 12.6 ns per loop (mean ± std. dev. of 3 runs, 100 loops each)
%%timeit
is for the code in the whole cell:
%%timeit
rng = range(1000000)
sum([x for x in rng])
# 63.4 ms ± 5.82 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
or (with some options provided)
%%timeit -n 100 -r 3
rng = range(1000000)
sum([x for x in rng])
# 62.6 ms ± 6.06 ms per loop (mean ± std. dev. of 3 runs, 100 loops each)
Upvotes: 0
Reputation: 21
You can accumulate the time taken to run. Something simple but useful.
Example:
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())
Result:
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
Upvotes: 0
Reputation: 583
You can do this to get the running time of each cell (similar to the ExecuteTime extension for Jupyter Notebook):
!pip install ipython-autotime
%load_ext autotime
This is how it'll look after running the above code:
Upvotes: 31
Reputation: 2066
You can check the execution time of absolutely anything by calculating the time taken
import time
t1 = time.perf_counter()
### Your code goes here ###
t2 = time.perf_counter()
print('time taken to run:',t2-t1)
Upvotes: 3
Reputation: 477
When you hover over the code block, you can see a sort of play button with a circular progression ring around while it's still running.
To track times, you can add %%timeit
at the start of the execution block like
%%timeit
for i in range(1000):
print(i)
# above is a placeholder for your code
and it will give you the time it took to run the code block in milliseconds.
Alternatively you can do %timeit l = [i for i in range(10)] #placeholder for a single line of code
to get the execution time for the single line.
Upvotes: 15