Test running time in Python

2021-12-21
#Unix #Python #Ubuntu

Python version: Python 2.7

System: MacOS, Ubuntu

1. time.clock

import time

def function():
    time.sleep(3)

start = time.clock()
function()
end = time.clock()

print('Running time: %s Seconds' % (end-start))

MacOS: Running time: 5.4e-05 Seconds

Ubuntu: Running time: 6.7e-05 Seconds

2. time.time

import time

def function():
    time.sleep(3)

start = time.time()
function()
end = time.time()

print('Running time: %s Seconds' % (end-start))

MacOS: Running time: 3.00427699089 Seconds

Ubuntu: Running time: 3.00312185287 Seconds

3. datetime.datetime.now

import datetime, time

def function():
    time.sleep(3)

start = datetime.datetime.now()
function()
end = datetime.datetime.now()

print('Running time: %s Seconds' % (end-start))

MacOS: Running time: 0:00:03.004322 Seconds

Ubuntu: Running time: 0:00:03.003236 Seconds

4. timeit.default_timer

import timeit, time

def function():
    time.sleep(3)

start = timeit.default_timer()
function()
end = timeit.default_timer()

print('Running time: %s Seconds' % (end-start))

MacOS: Running time: 3.00417017937 Seconds

Ubuntu: Running time: 3.0032479763 Seconds