Time the execution of Python code using syntax similar to MATLAB's tic and toc functions.
-
Basic usage:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> tt = TicToc()
>>> tt.tic()
>>> sleep(1.1)
>>> tt.toc()
Elapsed time: 1secs
-
Within context manager:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> with TicToc():
... sleep(1.1)
Elapsed time: 1secs
-
Within context manager using custom messages:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> with TicToc(begin_message="start", end_message="end"):
... sleep(1.1)
start
end: 1secs
-
Particularly helpful when running loops:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> with TicToc(begin_message="Start loop", end_message="Time to run loop")
... for value in ["first", "second", "Third"]:
... with TicToc(f"- Time for {value}"):
... sleep(1.1)
Start loop
- Time for first: 1secs
- Time for second: 1secs
- Time for Third: 1secs
Time to run loop: 3secs
-
Custom message:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> with TicToc("Total Time"):
... sleep(1.1)
Total time: 1secs
-
With restart during .tic()
:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> tt = TicToc()
>>> tt.tic(restart=True)
>>> sleep(1.1)
>>> toc()
Elapsed time: 1secs
>>> toc()
Elapsed time: 1secs
-
With restart during .toc()
:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> tt = TicToc()
>>> tt.tic()
>>> sleep(1.1)
>>> tt.toc(restart=True)
Elapsed time: 1secs
>>> tt.toc()
Elapsed time: 1secs
-
With restart using .rtoc()
:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> tt = TicToc()
>>> tt.tic()
>>> sleep(1.1)
>>> tt.rtoc()
Elapsed time: 1secs
>>> tt.toc()
Elapsed time: 1secs
-
With time returned as value:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> tt = TicToc()
>>> tt.tic()
>>> sleep(1.1)
>>> value = tt.toc_value()
>>> print(round(value, 1))
1.1
-
With time returned as string:
>>> from py_tictoc_timer.tictoc import TicToc
>>> from time import sleep
>>> tt = TicToc()
>>> tt.tic()
>>> sleep(1.1)
>>> value = tt.toc_string()
>>> print(value)
1secs