Search code examples
pythonperformanceruntimecomplexity-theory

How do I check running time?


What are the ways to time my Python code precisely, preferably using the built-in modules? Though algorithms are synonymous with efficient sorting, sometimes, adding a single digit to the input makes the code for one run incomprehensibly slower. One could not sit and wait for all that time.


Solution

  • You can encapsulate pieces of code in 'timed' box:

    t0 = time.time()
    <your code here>
    elapsed = time.time() - t0
    

    or use a profiler.

    The time solution is a little bit inefficient and profiler can be very dispersive in complex cases.

    Anyway if you can add a library, i'm the main developer of perf_tool very useful for these use cases.