Zidan
Zidan

Reputation: 135

How to properly use time.time()

I am trying to time a running function. But I need to know how many hours/minutes/seconds does it takes. I am using time.time(), but I don't understand the output. How can I convert this output in terms of how many hours/minutes/seconds does a function took? Or, if there is another proper library?

import time
starttime = time.time()
x=0
for i in range(100000):
    x+=i
endtime = time.time()
print('Job took: ', endtime-starttime)

Upvotes: 3

Views: 17577

Answers (3)

Code Pope
Code Pope

Reputation: 5459

time.time() gives the seconds when you started a process. Therefore endtime-starttime gives you the amount of seconds between the beginning and the end of the loop.
A preferable way to stop time in python is to use datetime:

import datetime
starttime = datetime.datetime.now()
x=0
for i in range(100000):
    x+=i
endtime = datetime.datetime.now()
diff = endtime - starttime
print('Job took: ', diff.days, diff.seconds, diff.microseconds)

Upvotes: 1

Samwise
Samwise

Reputation: 71542

I'd recommend using time.perf_counter instead of time.time, and using timedelta to format the units:

>>> from datetime import timedelta
>>> import time
>>> starttime = time.perf_counter()
>>> x=0
>>> for i in range(100000):
...     x+=i
...
>>> duration = timedelta(seconds=time.perf_counter()-starttime)
>>> print('Job took: ', duration)
Job took:  0:00:00.015017

The benefit of using perf_counter is that it won't be impacted by weird things like the timezone or system clock changing while you're measuring, and its resolution is guaranteed to be as high as possible (which may be important if you're timing very quick events).

In either case, the return value is measured in seconds, but you need to know what function it came from in order to know what the float value corresponds to. timedelta is a nicer way to represent a duration than a pure float IMO because it includes the units.

Upvotes: 6

Roy
Roy

Reputation: 1922

time.time():

The time() function returns the number of seconds passed since epoch.

For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).

import time
seconds = time.time()
print("Seconds since epoch =", seconds)

This might not be what you want

Upvotes: 1

Related Questions