Find out time it took for a python script to complete execution

Viewed 242800

I have the following code in a python script:

def fun(): 
  #Code here

fun()

I want to execute this script and also find out how much time it took to execute in minutes. How do I find out how much time it took for this script to execute ? An example would be really appreciated.

11 Answers

Pure Python

Better yet is time.perf_counter():

t0 = time.perf_counter()
fun()
t1 = time.perf_counter()
print(t1-t0)

# and if you really want your answer in minutes:
print(f"In minutes: {(t1-t0)/60}")

Recommended by this guy as well (5:30).

Docs:

time.perf_counter()→ float

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.

Use perf_counter_ns() to avoid the precision loss caused by the float type.

New in version 3.3.

Changed in version 3.10: On Windows, the function is now system-wide.


Jupyter Notebook: %timeit & %time magic

If you are working in a Jupyter Notebook (such as Google Colab), you can use IPython Magic Commands.

Example:

import time
import numpy as np
np.random.seed(42)

def fun(): 
    time.sleep(0.1+np.random.rand()*0.05)

Then in a separate cell, to time the function multiple times:

%timeit fun()

Output:

10 loops, best of 5: 120 ms per loop

To time the function only once:

%time fun()

Output:

CPU times: user 0 ns, sys: 621 µs, total: 621 µs
Wall time: 114 ms

You can find more about Magic Commands here.

use the time and datetime packages.

if anybody want to execute this script and also find out how much time it took to execute in minutes

import time
from time import strftime
from datetime import datetime 
from time import gmtime

def start_time_():    
    #import time
    start_time = time.time()
    return(start_time)

def end_time_():
    #import time
    end_time = time.time()
    return(end_time)

def Execution_time(start_time_,end_time_):
   #import time
   #from time import strftime
   #from datetime import datetime 
   #from time import gmtime
   return(strftime("%H:%M:%S",gmtime(int('{:.0f}'.format(float(str((end_time-start_time))))))))

start_time = start_time_()
# your code here #
[i for i in range(0,100000000)]
# your code here #
end_time = end_time_()
print("Execution_time is :", Execution_time(start_time,end_time))

The above code works for me. I hope this helps.

Here is the way I do this using functional programming - no global namespace pollution, proper inflection of plurals, only one function call at the very top of your script, all with only three imports, compatible with versions of Python starting from 3.6. I have this function in all my scripts:

import atexit
import re
import time


def time_script(): -> None
    """Local namespace to keep starting time as a free variable."""

    starting_time = 0.0

    @atexit.register
    def time_script_enclosed(): -> None
        """Time your scripts easily. Run in the very beginning of the script."""
        nonlocal starting_time

        if not starting_time:
            starting_time = time.perf_counter()
            print(time.strftime("%H:%M:%S", time.localtime()), end="")
            return print(": Starting script...")

        runtime = int(time.perf_counter() - starting_time)
        # Formatting with proper inflection of plurals
        runtime = time.strftime(
            "%#H hours, %#M minutes and %#S seconds", time.gmtime(runtime)
        )

        runtime = re.sub(r"^0 hours, ", "", runtime)
        runtime = re.sub(r"^1 hours", "1 hour", runtime)
        runtime = re.sub(r"(?=[^ ])0 minutes and ", "", runtime)
        runtime = re.sub(r"(?=[^ ])1 minutes", "1 minute", runtime)
        runtime = re.sub(r"(?=[^ ])1 seconds", "1 second", runtime)

        return print(f"The script took {runtime} to run.")

    time_script_enclosed()

Sample input:

def main():
    time_script()
    time.sleep(15)


if __name__ == '__main__':
    main()

Output:

20:58:28: Starting script...
The script took 15 seconds to run.

Sample input:

def main():
    time_script()
    time.sleep(61)


if __name__ == '__main__':
    main()

Output:

22:47:29: Starting script...
The script took 1 minute and 1 second to run.

Import timeit module and define the part of the script you want to time as function (e.g. main()).


    import timeit
    
    BF = timeit.timeit('BruteForce_MemoryEfficiency.main()', setup='import BruteForce_MemoryEfficiency', number=1)
    
    print(BF)

The function will be executed 1 time (number=1) and the time needed will be measured.

Related