Scripts to Measure Python Runtimes

One Time Test


import sys
from datetime import datetime

if __name__ == "__main__":
    print(f"Running {sys.argv[1]}")
    start_time = datetime.now()

    exec(open(sys.argv[1]).read())

    end_time = datetime.now()

    print(f"Total Runtime: {end_time - start_time}")

To use this script, simply run python <scriptname> <pythonfiletorun>

Multiple Time Test


import sys
from datetime import datetime

if __name__ == "__main__":
    print(f"Running {sys.argv[1]} {sys.argv[2]} time(s).")

    start_times = []
    end_times = []

    for i in range(0,int(sys.argv[2])):
        start_time = datetime.now()

        exec(open(sys.argv[1]).read())

        end_time = datetime.now()
        start_times.append(start_time)
        end_times.append(end_time)

    times = []
    i = 0
    while i<len(end_times):
        times.append(end_times[i] - start_times[i])
        i+=1
    
    print(f"Fastest Runtime: {min(times)}")

To run this script, simply run python <scriptname> <pythonfiletorun> <numberoftimes>… for example: python averagetime.py day1.py 40 would run day1.py 40 times, and return the fastest runtime.

Add a Comment

Your email address will not be published.