How can I accurately measure how long a function takes to run in Python?

I’m trying to figure out how to time a function in Python, but I’m not getting the expected results using timeit. Here’s what I tried: import timeit start = timeit.timeit() print(“hello”) end = timeit.timeit() print(end - start)

This doesn’t seem to measure the actual time taken between the two calls. What’s the correct way for to Python to time a function, either with timeit, time, or any other reliable method?

I’m looking for something simple that can help me check how long a specific block of code or function takes to execute. Any suggestions or corrections?

I’ve worked with time.time() quite a bit for quick checks on execution times. Here’s how I do it:

import time

start = time.time()
# Your function or code block
print("hello")
end = time.time()

print(f"Elapsed time: {end - start:.6f} seconds")

This gives you wall-clock time, which is great when you just need a general idea of the function’s runtime without worrying about nanosecond precision. I use this all the time for quick debugging or simple checks. It’s pretty reliable for most situations.

Absolutely, and I agree with @jacqueline-bosco on the simplicity of time.time(). However, for more precise measurements, especially when you’re timing small durations or testing multiple functions, I recommend using time.perf_counter() instead it provides a higher resolution. To make it cleaner, you can wrap the timing code in a decorator:

import time

def time_it(func):
    def wrapper(*args, **kwargs):
        start = time.perf_counter()
        result = func(*args, **kwargs)
        end = time.perf_counter()
        print(f"{func.__name__} took {end - start:.6f} seconds")
        return result
    return wrapper

@time_it
def my_function():
    print("hello")

my_function()

This way, you’re keeping your code reusable and elegant, and it works well if you’re testing multiple functions in your project.

You’re right, @charity-majors, time.perf_counter() definitely adds more accuracy to shorter durations. But if you’re really digging into micro-performance and need to see how your code behaves across repeated runs, you can use timeit.timeit(). It runs the code multiple times to get an accurate average. Here’s a quick setup:

import timeit

elapsed_time = timeit.timeit("print('hello')", number=1)
print(f"Elapsed time: {elapsed_time:.6f} seconds")

And for real functions, you can structure it like this:


def hello():
    print("hello")

elapsed = timeit.timeit(hello, number=1)
print(f"Function took: {elapsed:.6f} seconds")

This method is perfect when you want to benchmark small snippets of code or functions to get a more granular look at their performance over repeated executions.