Package: timeit-decorator
Timeit DecoratorOverviewtimeit_decoratoris a Python package providing a versatile decorator for timing the execution of functions. It
supports executing functions multiple times, in parallel, and can use either threading or multiprocessing depending on
the nature of the task.Efficient Execution for Single Run/WorkerThe decorator is optimized for scenarios where both runs and workers are set to 1. In such cases, it bypasses the
overhead of setting up a pool and directly executes the function, which is more efficient for single-run executions.Flexible LoggingThetimeit_decoratorcan either log timing information using Python's logging framework or print it directly to the
console. This behavior is controlled by thelog_levelparameter:If a log level is specified (e.g.,logging.INFO), the timing information will be logged at that level.Iflog_levelis set toNone, the timing information will be printed directly to the console.By default, thelog_levelparameter is set tologging.INFO.InstallationTo installtimeit_decorator, run the following command:pipinstalltimeit-decoratorUsageBasic UsageHere's how to use the timeit decorator:importloggingfromtimeit_decoratorimporttimeit# Configure logginglogging.basicConfig(level=logging.INFO)@timeit(runs=5,workers=2,log_level=logging.INFO)defsample_function():# Function implementationpass# Call the decorated functionsample_function()Efficient Execution for Single Run/WorkerFor single executions, the decorator directly runs the function:importloggingfromtimeit_decoratorimporttimeit# Configure logginglogging.basicConfig(level=logging.INFO)# Default parameters# @timeit(runs=1, workers=1, log_level=logging.INFO, use_multiprocessing=False)@timeit()defquick_function():# Function implementation for a quick taskpass# Call the decorated functionquick_function()Using MultiprocessingFor CPU-bound tasks, you can enable multiprocessing:importloggingfromtimeit_decoratorimporttimeit# Configure logginglogging.basicConfig(level=logging.DEBUG)@timeit(runs=10,workers=4,use_multiprocessing=True,log_level=logging.DEBUG)defcpu_intensive_function():# CPU-bound function implementationpass# Call the decorated functioncpu_intensive_function()Using Threading (Default)For I/O-bound tasks, the default threading is more efficient:importloggingfromtimeit_decoratorimporttimeit# Configure logginglogging.basicConfig(level=logging.INFO)@timeit(runs=5,workers=2)defio_bound_function():# I/O-bound function implementationpass# Call the decorated functionio_bound_function()Detailed Output OptionThetimeitdecorator includes an optional detailed parameter that provides more extensive statistics about the
function
execution time when set to True. This feature is particularly useful for in-depth performance analysis and debugging, as
it gives users a broader view of how the function behaves under different conditions.Usage of thedetailedParameterPurpose: When set to True, the timeit decorator provides a detailed tabulated output including average, median,
minimum,
and maximum execution times, standard deviation, and total execution time for all runs.Example@timeit(runs=5,workers=2,detailed=True)defsample_function(a,b,c="some value"):# Function implementationpasssample_function("arg1","arg2",key="value")This will output a detailed tabulated summary after the function execution, similar to the following:Function       sample_function
Args           ('arg1', 'arg2')
Kwargs         {'key': 'value'}
Runs           5
Workers        2
Average Time   0.2s
Median Time    0.19s
Min Time       0.18s
Max Time       0.22s
Std Deviation  0.015s
Total Time     1.0sUse CasesPerformance Analysis: Use thedetailedparameter to get a comprehensive overview of the function's performance
across multiple runs.Debugging: The detailed statistics can help identify inconsistencies or anomalies in function execution, aiding in
debugging efforts.Remember that enabling detailed output can increase the verbosity of the output, especially for functions executed
multiple times. It is recommended to use this feature judiciously based on the specific needs of performance analysis or
debugging.FeaturesMultiple Runs and Workers: Execute the function multiple times in parallel for more accurate timing.Flexible Logging: Choose between logging framework or direct print to console for output.Optimized for Single Execution: Efficient for single run/worker scenarios.Supports Multiprocessing and Threading: Suitable for both CPU-bound and I/O-bound tasks.LimitationsWhile thetimeitdecorator is designed to be versatile and useful in a wide range of scenarios, there are certain
limitations that users should be aware of:Incompatibility with Static Methods and MultiprocessingStatic Methods and Multiprocessing: Thetimeitdecorator currently does not support the use of multiprocessing (use_multiprocessing=True) with@staticmethod. Attempting to use thetimeitdecorator with multiprocessing on
static
methods can lead to unexpected behavior or errors, specifically aPicklingError.Reason for the Limitation: This issue arises because Python's multiprocessing module requires objects to be
serialized (pickled) for transfer between processes. However, static methods pose a challenge for Python's pickling
mechanism due to the way they are referenced internally. This can result in aPicklingErrorstating that the static
method is not the same object as expected.Example of the issue:# This will raise a PicklingError when executedclassExampleClass:@staticmethod@timeit(use_multiprocessing=True,runs=2)defexample_static_method():# method implementationpassExample of exception :_pickle.PicklingError: Can't pickle <function ExampleClass.example_static_method at 0x...>: it's not the same object as __main__.ExampleClass.example_static_methodRecommended Workaround:To avoid this issue, consider using instance methods or regular functions, which are not
subject to the same serialization constraints as static methods. Alternatively, refrain from usinguse_multiprocessing=Truewith static methods.This limitation stems from inherent characteristics of Python's multiprocessing and pickling mechanisms. Users are
encouraged to structure their code accordingly to prevent encountering this issue. We are continuously working to
enhance thetimeitdecorator and mitigate such limitations wherever possible. If you encounter any other issues or
limitations, please feel free to report them in the project's issue tracker.Requirementstimeit_decoratorrequires Python 3.x.ContributingContributions totimeit_decoratorare welcome! Please read ourcontributing guidelinesfor more
details.Licensetimeit_decoratoris released under theMIT License.