HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Measuring Execution Times

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
timesexecutionmeasuring

Problem

I was wondering which time.time() of from datetime import timedelta was the quickest and best way to find how long a programme had been running for example.

import time
start = time.time()

#do stuff

print(start - time.time())


or (although longer)

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms
def tickscheck(start):
    x = 0
    count = 0
    while millis() - start < 1000:
        x = 4+5
        #counting up
        count = count + 1
        print("It Took " + str(count) + " Counts\nOver " + str(millis()- start) + "ticks")

running = True
while(running == True):
    tickscheck(millis())

Solution

In Python 3.3 and later you can use one of


time.perf_counter()

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
consecutive calls is valid.


time.process_time()
Return the value (in fractional seconds) of the
sum of the system and user CPU time of the current process. It does
not include time elapsed during sleep. It is process-wide by
definition. The reference point of the returned value is undefined, so
that only the difference between the results of consecutive calls is
valid.

Older Python versions offer timeit.default_timer(), which is now an alias of time.perf_counter().

The timeit module offers tools to get more reliable timings by running the code multiple times.

Context

StackExchange Code Review Q#48416, answer score: 9

Revisions (0)

No revisions yet.