Use time.time() to measure the elapsed wall-clock time between two points:

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

This gives the execution time in seconds.


Another option since Python 3.3 might be to use perf_counter or process_time, depending on your requirements. Before 3.3 it was recommended to use time.clock (thanks Amber). However, it is currently deprecated:

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.

Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

Answer from NPE on Stack Overflow
Top answer
1 of 16
2637

Use time.time() to measure the elapsed wall-clock time between two points:

import time

start = time.time()
print("hello")
end = time.time()
print(end - start)

This gives the execution time in seconds.


Another option since Python 3.3 might be to use perf_counter or process_time, depending on your requirements. Before 3.3 it was recommended to use time.clock (thanks Amber). However, it is currently deprecated:

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.

Deprecated since version 3.3: The behaviour of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well defined behaviour.

2 of 16
1222

Use timeit.default_timer instead of timeit.timeit. The former provides the best clock available on your platform and version of Python automatically:

from timeit import default_timer as timer

start = timer()
# ...
end = timer()
print(end - start) # Time in seconds, e.g. 5.38091952400282

timeit.default_timer is assigned to time.time() or time.clock() depending on OS. On Python 3.3+ default_timer is time.perf_counter() on all platforms. See Python - time.clock() vs. time.time() - accuracy?

See also:

  • Optimizing code
  • How to optimize for speed
🌐
Real Python
realpython.com › python-timer
Python Timer Functions: Three Ways to Monitor Your Code – Real Python
December 8, 2024 - A timer is a powerful tool for monitoring the performance of your Python code. By using the time.perf_counter() function, you can measure execution time with exceptional precision, making it ideal for benchmarking.
🌐
Python
docs.python.org › 3 › library › timeit.html
timeit — Measure execution time of small code snippets
In a typical case, the lowest value gives a lower bound for how fast your machine can run the given code snippet; higher values in the result vector are typically not caused by variability in Python’s speed, but by other processes interfering with your timing accuracy. So the min() of the result is probably the only number you should be interested in. After that, you should look at the entire vector and apply common sense rather than statistics. Changed in version 3.7: Default value of repeat changed from 3 to 5. ... Helper to print a traceback from the timed code. ... t = Timer(...) # outside the try/except try: t.timeit(...) # or t.repeat(...) except Exception: t.print_exc()
🌐
Built In
builtin.com › articles › timing-functions-python
Timing Functions in Python: A Guide | Built In
You can time Python functions to measure how long it takes for your Python code to run or evaluate the performance of different approaches using time.perf)counter(), time.time() and more.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-measure-time-taken-by-program-to-execute
Measure time taken by program to execute in Python - GeeksforGeeks
July 15, 2025 - default_timer() function from the timeit module gives the most accurate clock depending on the platform. It is ideal for benchmarking small blocks of code. Python · from timeit import default_timer as timer start = timer() for _ in range(100): ...
🌐
Switowski
switowski.com › blog › how-to-benchmark-python-code
How to Benchmark (Python) Code
November 17, 2022 - You can write python -m timeit your_code(), and Python will print out how long it took to run whatever your_code() does. I like to put the code I want to benchmark inside a function for more clarity, but you don't have to do this.
🌐
Towards Data Science
towardsdatascience.com › home › latest › benchmarking python code with timeit
Benchmarking Python code with timeit | Towards Data Science
March 5, 2025 - timer is the timer used; the default one is perf_counter(), and since it’s currently considered the best built-in timer, in most situations it’s best not to touch it; repeat is the number of sessions to be run, each session consisting of ...
Find elsewhere
🌐
Jakob-bagterp
jakob-bagterp.github.io › timer-for-python › user-guide › tips-and-trick › measure-start-and-stop-time
The Easy Way to Measure Start and Stop Time - Timer for Python ⏳
June 2, 2025 - Learn how to measure elapsed time of your Python code like a stop watch. Includes code examples for beginners and advanced users.
🌐
Super Fast Python
superfastpython.com › home › tutorials › benchmark python with time.process_time()
Benchmark Python with time.process_time() - Super Fast Python
September 29, 2023 - We will then surround this statement with benchmarking code. Firstly, we will record the start time using the time.process_time() function. Afterward, we will record the end time, calculate the overall execution duration, and report the result. Tying this together, the complete example is listed below. Running the example first records the start time, a number from an internal clock for the process. Next, the Python statement is executed, in this case creating a list of 100 million squared integers.
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-measure-elapsed-time-in-python
How to Measure Elapsed Time in Python - GeeksforGeeks
July 23, 2025 - time.perf_counter() provides the highest available resolution timer in Python, ideal for measuring short durations.
🌐
GitHub
github.com › belm0 › perf-timer
GitHub - belm0/perf-timer: An indispensable performance timer for Python
The smaller the timer's overhead, the less it interferes with the normal timing of your program, and the tighter the code loop it can be applied to. The values below represent the typical overhead of one observation, as measured on ye old laptop (2014 MacBook Air 11 1.7GHz i7). $ pip install -r test-requirements.txt $ python benchmarks/overhead.py compare observers: PerfTimer(observer=AverageObserver): 1.5 µs PerfTimer(observer=StdDevObserver): 1.8 µs (default) PerfTimer(observer=HistogramObserver): 6.0 µs compare types: PerfTimer(observer=StdDevObserver): 1.8 µs ThreadPerfTimer(observer=StdDevObserver): 9.8 µs TrioPerfTimer(observer=StdDevObserver): 4.8 µs
Starred by 24 users
Forked by 4 users
Languages   Python 98.7% | Makefile 1.3% | Python 98.7% | Makefile 1.3%
🌐
Sentry
sentry.io › sentry answers › python › measure elapsed time in python
Measure elapsed time in Python | Sentry
July 15, 2023 - We can do this using the perf_counter function in Python’s built-in time module.
🌐
Super Fast Python
superfastpython.com › home › tutorials › 4 ways to benchmark python code
4 Ways to Benchmark Python Code - Super Fast Python
October 4, 2023 - You can benchmark Python code using the Python standard library. Code can be benchmarked manually using the time module. The timeit module provides functions for automatically benchmarking code.
🌐
PyTorch
docs.pytorch.org › reference api › benchmark utils - torch.utils.benchmark
Benchmark Utils - torch.utils.benchmark — PyTorch 2.11 documentation
class torch.utils.benchmark.Timer(stmt='pass', setup='pass', global_setup='', timer=<built-in function perf_counter>, globals=None, label=None, sub_label=None, description=None, env=None, num_threads=1, language=Language.PYTHON)[source]#
🌐
GitHub
github.com › pytorch › tutorials › blob › main › recipes_source › recipes › benchmark.py
tutorials/recipes_source/recipes/benchmark.py at main · pytorch/tutorials
# 2. Benchmarking with ``timeit.Timer`` # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # First, let's benchmark the code using Python's builtin ``timeit`` module. # We keep the benchmark code simple here so we can compare the defaults · # of ``timeit`` and ``torch.utils.benchmark``. # ·
Author   pytorch
🌐
Reddit
reddit.com › r/learnpython › benchmark timer & timeout decorator?
r/learnpython on Reddit: Benchmark timer & timeout decorator?
November 15, 2018 -

Hello,

I've written a few different implementations of a program that I would like to do some benchmark comparisons. I have a list of growing inputs and a set of configurations to run. I am iterating over the growing inputs and then iterating over the configurations internally.

I used cProfile to get general performance comparisons, but I'd like to generate some performance curves for each program.

I've written a simple decorator that modifies the output to return the return value and runtime.

However, I'd like the program to raise an Exception if the program takes too long. That way I can catch the exception, complete the current iteration of configurations and then kill the loop.

I haven't found anything like this online, but is there anything like this? It seems like it would be a pretty generic utility function. How could/should I implement a timeout decorator?

Here is a snippet of my benchmarking iteration:

    # if the function ever times out, kill the loop after completing for all starting positions
    timeoutFailure = False

    for turn in turns:
        results = [turn]

        for case in cases:
            try:
                return value, runtime = testFunction(case, turn)

            except Exception:
                runtime = -1
                timeoutFailure = True

            results = results + [runtime]

        BenchmarkWriter.writerow(results)

        if timeoutFailure:
            break

And here is my benchmarking decorator:

import random
import time
 
def timerfunc(func):
    """
    A timer decorator
    """
    def function_timer(*args, **kwargs):
        """
        A nested function for timing other functions
        """
        start = time.time()
        value = func(*args, **kwargs)
        end = time.time()
        
        runtime = end - start

        return value, runtime
    return function_timer
🌐
PYnative
pynative.com › home › python › python datetime › python measure the execution time of a program
Python Get Execution Time of a Program [5 Ways] – PYnative
February 23, 2022 - timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)Code language: Python (python)
🌐
TutorialsPoint
tutorialspoint.com › concurrency_in_python › concurrency_in_python_benchmarking_and_profiling.htm
Benchmarking & Profiling
In other words, we can understand it as breaking the big and hard problem into series of smaller and a bit easier problems for optimizing them. In Python, we have a by default module for benchmarking which is called timeit.
🌐
Hamilton Place
hamiltonplace.com › home › store: barnes and noble
Python Benchmarking: Measure The Execution Time Of ...
Explore an extensive range of products from Barnes and Noble available at Hamilton Place in Chattanooga, TN