Update the timeit function to use the timeit module

add the autorange function as a bonus (I like it better)
This commit is contained in:
Gouvernathor 2023-11-11 21:02:36 +01:00
parent b6d07aaa99
commit dbda53d19a

View File

@ -11,6 +11,7 @@ init python early:
import re import re
import string import string
import functools import functools
import timeit as timeit_module
from bisect import bisect from bisect import bisect
from operator import itemgetter from operator import itemgetter
from operator import add as _add from operator import add as _add
@ -138,11 +139,12 @@ init python early:
return False return False
def timeit(func, loops=10000, args=(), kwargs={}): def timeit(func, loops=10000, args=(), kwargs={}):
start = time.time() rv = timeit_module.timeit("func(*args, **kwargs)", number=loops, globals=dict(func=func, args=args, kwargs=kwargs))
for i in range(loops): print(f"The task has taken {rv} seconds to finish")
func(*args, **kwargs)
end = time.time() def autorange(func, args=(), kwargs={}):
print(f"The task has taken {end-start} seconds to finish") loops, time = timeit_module.Timer("func(*args, **kwargs)", globals=dict(func=func, args=args, kwargs=kwargs)).autorange()
print(f"The task has taken {time/loops} seconds to finish ({loops} iterations in {time} seconds)")
def list_swap_values(l, val1, val2): def list_swap_values(l, val1, val2):
"""Mutates the original list.""" """Mutates the original list."""
@ -222,4 +224,4 @@ init python early:
return len(self._callable()) return len(self._callable())
def execute_callbacks(callbacks): def execute_callbacks(callbacks):
for callback in callbacks: callback() for callback in callbacks: callback()