The time module provides access to several different types of clocks, each useful for different purposes. The standard system calls like time() report the system “wall clock” time. The monotonic() clock can be used to measure elapsed time in a long-running process because it is guaranteed never to move backwards, even if the system time is changed. For performance testing, perf_counter() provides access to the clock with the highest available resolution to make short time measurements more accurate. The CPU time is available through clock(), and process_time() returns the combined processor time and system time.

Comparing Clocks


In [5]:
import textwrap
import time

available_clocks = [
    ('clock', time.clock),
    ('monotonic', time.monotonic),
    ('perf_counter', time.perf_counter),
    ('process_time', time.process_time),
    ('time', time.time),
]

for clock_name, func in available_clocks:
    print(textwrap.dedent('''\
    {name}:
        adjustable    : {info.adjustable}
        implementation: {info.implementation}
        monotonic     : {info.monotonic}
        resolution    : {info.resolution}
        current       : {current}
    ''').format(
        name=clock_name,
        info=time.get_clock_info(clock_name),
        current=func())
    )


clock:
    adjustable    : False
    implementation: clock()
    monotonic     : True
    resolution    : 1e-06
    current       : 1.394774

monotonic:
    adjustable    : False
    implementation: mach_absolute_time()
    monotonic     : True
    resolution    : 1e-09
    current       : 1097416.716575929

perf_counter:
    adjustable    : False
    implementation: mach_absolute_time()
    monotonic     : True
    resolution    : 1e-09
    current       : 1097416.716700798

process_time:
    adjustable    : False
    implementation: getrusage(RUSAGE_SELF)
    monotonic     : True
    resolution    : 1e-06
    current       : 1.3963050000000001

time:
    adjustable    : True
    implementation: gettimeofday()
    monotonic     : False
    resolution    : 1e-06
    current       : 1504355935.276109

Wall Clock Time


In [6]:
import time
print('The Time is:', time.time())


The Time is: 1504356004.558045

In [7]:
import time
print('The time is   :', time.ctime())
later = time.time() + 15
print('15 secs from now:', time.ctime(later))


The time is   : Sat Sep  2 20:41:39 2017
15 secs from now: Sat Sep  2 20:41:54 2017

Monotonic Clocks


In [10]:
import time
start = time.monotonic()
time.sleep(0.1)
end = time.monotonic()
print('Start: {:>9.2f}'.format(start))
print('End: {:>9.2f}'.format(end))
print('Span: {:>9.2f}'.format(end-start))


Start: 1097775.91
End: 1097776.01
Span:      0.10

Processor Clock Time


In [13]:
import hashlib
import time
data = open('time.ipynb', 'rb').read()
for i in range(5):
    h = hashlib.sha1()
    print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
        time.time(), time.clock()))
    for i in range(300000):
        h.update(data)
    cksum=h.digest()


Sat Sep  2 20:48:19 2017 : 1504356499.596 1.527
Sat Sep  2 20:48:22 2017 : 1504356502.767 4.670
Sat Sep  2 20:48:25 2017 : 1504356505.899 7.793
Sat Sep  2 20:48:29 2017 : 1504356509.036 10.919
Sat Sep  2 20:48:32 2017 : 1504356512.197 14.072

In [14]:
import time

template = '{} - {:0.2f} - {:0.2f}'

print(template.format(
    time.ctime(), time.time(), time.clock())
)

for i in range(3, 0, -1):
    print('Sleeping', i)
    time.sleep(i)
    print(template.format(
        time.ctime(), time.time(), time.clock())
    )


Sat Sep  2 20:49:07 2017 - 1504356547.32 - 17.20
Sleeping 3
Sat Sep  2 20:49:10 2017 - 1504356550.33 - 17.20
Sleeping 2
Sat Sep  2 20:49:12 2017 - 1504356552.33 - 17.21
Sleeping 1
Sat Sep  2 20:49:13 2017 - 1504356553.33 - 17.21

Performance Counter


In [16]:
import hashlib
import time

# Data to use to calculate md5 checksums
data = open('time.ipynb', 'rb').read()

loop_start = time.perf_counter()

for i in range(5):
    iter_start = time.perf_counter()
    h = hashlib.sha1()
    for i in range(300000):
        h.update(data)
    cksum = h.digest()
    now = time.perf_counter()
    loop_elapsed = now - loop_start
    iter_elapsed = now - iter_start
    print(time.ctime(), ': {:0.3f} {:0.3f}'.format(
        iter_elapsed, loop_elapsed))


Sat Sep  2 20:50:45 2017 : 3.028 3.028
Sat Sep  2 20:50:48 2017 : 2.864 5.893
Sat Sep  2 20:50:50 2017 : 2.911 8.804
Sat Sep  2 20:50:53 2017 : 2.848 11.652
Sat Sep  2 20:50:56 2017 : 2.874 14.527

Time Components


In [18]:
import time


def show_struct(s):
    print('  tm_year :', s.tm_year)
    print('  tm_mon  :', s.tm_mon)
    print('  tm_mday :', s.tm_mday)
    print('  tm_hour :', s.tm_hour)
    print('  tm_min  :', s.tm_min)
    print('  tm_sec  :', s.tm_sec)
    print('  tm_wday :', s.tm_wday)
    print('  tm_yday :', s.tm_yday)
    print('  tm_isdst:', s.tm_isdst)

print('gmtime:')
show_struct(time.gmtime())
print('\nlocaltime:')
show_struct(time.localtime())
print('\nmktime:', time.mktime(time.localtime()))


gmtime:
  tm_year : 2017
  tm_mon  : 9
  tm_mday : 2
  tm_hour : 12
  tm_min  : 52
  tm_sec  : 16
  tm_wday : 5
  tm_yday : 245
  tm_isdst: 0

localtime:
  tm_year : 2017
  tm_mon  : 9
  tm_mday : 2
  tm_hour : 20
  tm_min  : 52
  tm_sec  : 16
  tm_wday : 5
  tm_yday : 245
  tm_isdst: 0

mktime: 1504356736.0

Working with Time Zones


In [19]:
import time
import os


def show_zone_info():
    print('  TZ    :', os.environ.get('TZ', '(not set)'))
    print('  tzname:', time.tzname)
    print('  Zone  : {} ({})'.format(
        time.timezone, (time.timezone / 3600)))
    print('  DST   :', time.daylight)
    print('  Time  :', time.ctime())
    print()


print('Default :')
show_zone_info()

ZONES = [
    'GMT',
    'Europe/Amsterdam',
]

for zone in ZONES:
    os.environ['TZ'] = zone
    time.tzset()
    print(zone, ':')
    show_zone_info()


Default :
  TZ    : (not set)
  tzname: ('CST', 'CST')
  Zone  : -28800 (-8.0)
  DST   : 0
  Time  : Sat Sep  2 20:53:53 2017

GMT :
  TZ    : GMT
  tzname: ('GMT', 'GMT')
  Zone  : 0 (0.0)
  DST   : 0
  Time  : Sat Sep  2 12:53:53 2017

Europe/Amsterdam :
  TZ    : Europe/Amsterdam
  tzname: ('CET', 'CEST')
  Zone  : -3600 (-1.0)
  DST   : 1
  Time  : Sat Sep  2 14:53:53 2017