Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring elapsed time with the Time module

With the Time module in python is it possible to measure elapsed time? If so, how do I do that?

I need to do this so that if the cursor has been in a widget for a certain duration an event happens.

like image 308
rectangletangle Avatar asked Sep 01 '10 18:09

rectangletangle


People also ask

How do you measure elapsed time?

In simple words, we can say that the amount of time that has passed between the beginning and the end of an event is called the elapsed time. We can determine this time by subtracting the end time and the start time. The formula to calculate the elapsed time is simply to subtract the hours and minutes separately.

What are used to measure the elapsed time of events?

How do you calculate elapsed time? Calculating elapsed time can be done by measuring the time between the start and finish of an event. This can be done by the use of simple addition or subtraction.

How do you measure time in nanoseconds Python?

time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time. time() method. The epoch is the point where the time starts and is platform dependent.

How does Python measure time in MS?

Use datetime. timedelta. total_seconds() to get the execution time of code in milliseconds.


4 Answers

start_time = time.time()
# your code
elapsed_time = time.time() - start_time

You can also write simple decorator to simplify measurement of execution time of various functions:

import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()

        ret = fn(*args, **kwargs)

        elapsed_time = time.time() - start_time

        if fn.__name__ not in PROF_DATA:
            PROF_DATA[fn.__name__] = [0, []]
        PROF_DATA[fn.__name__][0] += 1
        PROF_DATA[fn.__name__][1].append(elapsed_time)

        return ret

    return with_profiling

def print_prof_data():
    for fname, data in PROF_DATA.items():
        max_time = max(data[1])
        avg_time = sum(data[1]) / len(data[1])
        print "Function %s called %d times. " % (fname, data[0]),
        print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
    global PROF_DATA
    PROF_DATA = {}

Usage:

@profile
def your_function(...):
    ...

You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():

like image 175
Vadim Shender Avatar answered Oct 04 '22 19:10

Vadim Shender


time.time() will do the job.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start

You may want to look at this question, but I don't think it will be necessary.

like image 25
lalli Avatar answered Oct 04 '22 19:10

lalli


For users that want better formatting,

import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))

will print out, for 2 seconds:

'00:00:02'

and for 7 minutes one second:

'00:07:01'

note that the minimum time unit with gmtime is seconds. If you need microseconds consider the following:

import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds) 

strftime documentation

like image 33
Rutger Hofste Avatar answered Oct 04 '22 19:10

Rutger Hofste


For the best measure of elapsed time (since Python 3.3), use 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.

For measurements on the order of hours/days, you don't care about sub-second resolution so use time.monotonic() instead.

Return the value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. The clock is not affected by system clock updates. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

In many implementations, these may actually be the same thing.

Before 3.3, you're stuck with time.clock().

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.


Update for Python 3.7

New in Python 3.7 is PEP 564 -- Add new time functions with nanosecond resolution.

Use of these can further eliminate rounding and floating-point errors, especially if you're measuring very short periods, or your application (or Windows machine) is long-running.

Resolution starts breaking down on perf_counter() after around 100 days. So for example after a year of uptime, the shortest interval (greater than 0) it can measure will be bigger than when it started.


Update for Python 3.8

time.clock is now gone.

like image 40
OrangeDog Avatar answered Oct 04 '22 20:10

OrangeDog