SoFunction
Updated on 2025-05-12

Five ways to calculate the execution time of a function in Python

1. ()

When calculating the execution time of a function, this is the most concise way to subtract two timestamps.

import time


def func():
    print('func start')
    (1)
    print('func end')


t = ()
func()
print(f'coast:{() - t:.4f}s')

The result is:

func start
func end
coast:1.0003s

This method is simple and commonly used, but if you want to calculate the execution time of the function more accurately, it will cause the accuracy loss.

2. time.perf_counter() Recommended

Comment out (1) in Example 1, and only count the execution time of the two print functions:

import time


def func():
    print('func start')
    # (1)
    print('func end')


t = ()
func()
print(f'coast:{() - t:.8f}s')

Output:

func start
func end
coast:0.0000s

This shows that the accuracy of the () function is not particularly high, and it is impossible to count the time-consuming function with extremely short execution time.

The perf_counter function is newly added in python3.3. It returns the value of the performance counter. The return value is floating point type. The statistical result includes the time of sleep. The return value of a single function is meaningless. Only the result of multiple runs to get the difference is the valid function execution time.

import time


def func():
    print('func start')
    # (1)
    print('func end')


t = time.perf_counter()
func()
print(f'coast:{time.perf_counter() - t:.8f}s')

result

func start
func end
coast:0.00001500s

The result is not 0 seconds, but a very small value. This shows that the perf_counter() function can count the execution time of the print function and the statistical accuracy is higher than that of the () function. It is recommended to use it as a timer.

3. ()

The timeit() function has 5 parameters, stmt='pass', setup='pass', timer=, number=1000000, globals=None.

  • The stmt parameter is a statement that needs to be executed, and the default is pass
  • The setup parameter is a statement used to execute initialization code or build environment. The default is pass
  • timer is a timer, the default is perf_counter()
  • number is the number of executions, defaulting to one million
  • globals is used to specify the namespace to run the code, and the default is None.
import time
import timeit


def func():
    print('func start')
    (1)
    print('func end')


print((stmt=func, number=1))

The recommended use of the time.perf_counter() function in the above scheme is the time.perf_counter() function, which has relatively high precision and is also used as the default timer for the timeit function.

4. Decorator statistics operation time

In actual project code, it can be run time-consuming through the decorator's convenient statistical functions.

import time


def cost_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    return fun


@cost_time
def test():
    print('func start')
    (2)
    print('func end')


if __name__ == '__main__':
    test()

If you have the requirement to use asynchronous functions, you can also add:

import asyncio
import time
from  import iscoroutinefunction


def cost_time(func):
    def fun(*args, **kwargs):
        t = time.perf_counter()
        result = func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    async def func_async(*args, **kwargs):
        t = time.perf_counter()
        result = await func(*args, **kwargs)
        print(f'func {func.__name__} cost time:{time.perf_counter() - t:.8f} s')
        return result

    if iscoroutinefunction(func):
        return func_async
    else:
        return fun


@cost_time
def test():
    print('func start')
    (2)
    print('func end')


@cost_time
async def test_async():
    print('async func start')
    await (2)
    print('async func end')


if __name__ == '__main__':
    test()
    asyncio.get_event_loop().run_until_complete(test_async())

The benefit of using a decorator to count the time-consuming execution of a function is that it is less invasive and easy to write and modify.

The decorator decorating function scheme is only suitable for the time-consuming operation of statistical functions. If there is a time-consuming and statistical requirement for code blocks, it cannot be used. In this case, we can use the with statement to automatically manage the context.

5. With statement statistics to run time

Implementing the enter and exit functions allows us to perform some custom actions when entering and exiting the context, such as connecting/disconnecting the database, opening/closing the file, recording the start/end time, etc. Here we use it to count the execution time of the function block.

import asyncio
import time


class CostTime(object):
    def __init__(self):
         = 0

    def __enter__(self):
         = time.perf_counter()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f'cost time:{time.perf_counter() - :.8f} s')


def test():
    print('func start')
    with CostTime():
        (2)
        print('func end')


async def test_async():
    print('async func start')
    with CostTime():
        await (2)
        print('async func end')


if __name__ == '__main__':
    test()
    asyncio.get_event_loop().run_until_complete(test_async())

The with statement can not only count the execution time of the code block, but also count the execution time of the function, and also count the sum of the execution time of multiple functions. Compared with the decorator, it is more invasive to the code and is not easy to modify. The advantage is that it is more flexible to use and does not need to write too much repetitive code.

6. Extension: Python implements function timeout exit

Method 1

import time
import eventlet#Import eventlet moduleeventlet.monkey_patch()#This code must be addedwith (5,False):#Set the timeout to 2 seconds  (4)
  print('This output was not skipped')
print('Skipped output')

The second method is not very good at using it, and if you fail to use it, it is worse than the first one

import time
import timeout_decorator

@timeout_decorator.timeout(5)
def mytest():
    print("Start")
    for i in range(1,10):
        (1)
        print("{} seconds have passed".format(i))

if __name__ == '__main__':
    mytest()

Python setting function call timeout

import time
import signal
def test(i):
(i%4)
print "%d within time"%(i)
return i
if __name__ == '__main__':
def handler(signum, frame):
raise AssertionError
i = 0
for i in range(1,10):
try:
(, handler)
(3)
test(i)
i = i + 1
(0)
except AssertionError:
print "%d timeout"%(i)

illustrate:

1. Call the test function to timeout monitoring, use the sleep simulation function to execute timeout

2. Introduce the signal module, set the handler to capture the timeout information, and return the assertion error

3. alarm(3), set the alarm clock for 3 seconds, and return directly if the function call timeout is 3 seconds.

4. Catch exceptions and print timeout information

Execution results

within time
within time
timeout
within time
within time
within time
timeout
within time
within time

This is the end of this article about five methods for calculating function execution time in Python. For more related content on calculating function execution time of Python, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!