[docs]defformat_timedelta(td:timedelta)->str:"""Format a timedelta in a "human-readable" way"""# Determine the total amount of secondstotal_seconds=int(td.total_seconds())hours,remainder=divmod(total_seconds,3600)minutes,seconds=divmod(remainder,60)# Get the total microseconds remainingmicroseconds=td.microseconds# Format based on the most significant unitifhours>0:returnf'{hours}h {minutes}m {seconds}s'ifminutes>0:returnf'{minutes}m {seconds}s'ifseconds>0:returnf'{seconds}.{microseconds//100000:01}s'ifmicroseconds>=1000:returnf'{microseconds//1000}ms'# Convert to millisecondsreturnf'{microseconds}μs'# Microseconds as is
[docs]classTiming:"""Call for timing the execution of callable functions"""def__init__(self,warm_up_runs:int=10,num_runs:int=100):self._warm_up_runs=warm_up_runsself._num_runs=num_runs@propertydefwarm_up_runs(self)->int:returnself._warm_up_runs@warm_up_runs.setterdefwarm_up_runs(self,value:int):ifvalue<0:raiseValueError("warm_up_runs must be non-negative")self._warm_up_runs=value@propertydefnum_runs(self)->int:returnself._num_runs@num_runs.setterdefnum_runs(self,value:int):ifvalue<1:raiseValueError("num_runs must be at least 1")self._num_runs=value
[docs]deftime_function(self,callable_func:Callable,kwargs:dict[str,Any],)->float:""" Times the execution of a callable function, excluding the warm-up period. :param callable_func: The function to be timed. :param kwargs: Dictionary of keyword arguments to pass to the function. Note that all arguments must be with keyword :return: Average time per run. """# Warm-up periodforiinrange(self.warm_up_runs):callable_func(**kwargs)# Timing the functionstart_time=time.time()for_intqdm(range(self.num_runs)):callable_func(**kwargs)end_time=time.time()# Calculate the average time per runtotal_time=end_time-start_timeaverage_time_per_run=total_time/self.num_runsreturnaverage_time_per_run