Simple python timer to use for single lines of code, or entire functions/classes
- Use
code_timer.Timer
as a class, context manager, decorator- Offers the most versatility and flexibility for your needs
- Use separate
code_timer.timer
decorator - Use
code_timer.timeit
decorator to measure the time to run the same function multiple times- Useful when comparing the efficiency of one runtime vs another
- By default, will run the function 10,000 times. The number of runs is configurable
- DO NOT USE THIS FOR RECURSIVE FUNCTIONS!!
- Logger allowing you to set the streaming level or hide the logging entirely
-
As a class:
t = Timer(name="class") t.start() # Do something t.stop()
-
As a context manager:
-
Useful when trying to time a recursive function
with Timer(name="context manager") as t: # Do something print(f"Elapsed time: {t.elapsed_time}")
-
As a decorator:
@Timer(name="decorator") def stuff(): # Do something
-
Without braces
@timer def your_func(): # Do something
-
With braces
@timer(name="my_timer") def your_func(): # Do something
- Time is reported at logging level: logging.INFO
- The following assumes the standard formatting for the code_timer logger
-
Default
- will repeat the function 10,000 times and report the fastest three runs
@timeit def your_func(): # Do something
- Output:
2020-03-12 21:56:46: code_timer.INFO - Best 3 of 10000 for your_func: 0.2200 ms; 0.2220 ms; 0.2232 ms
-
Pass in the number of times to repeat
@timeit(num_repeats=50) def your_func(): # Do something
- Output:
2020-03-12 21:56:46: code_timer.INFO - Best 3 of 50 for your_func: 0.2200 ms; 0.2220 ms; 0.2232 ms
- Output: