Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to add time delay in Python?
Next article icon

How to Measure Elapsed Time in Python

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, we can measure the elapsed time (time taken for a specific task to complete) on executing a code segment or a Python script. It's useful when we are benchmarking the code, debugging or optimizing performance.

Python provides several built-in modules to measure the execution time of code blocks:

  • timeit: Best for benchmarking small code snippets.
  • time: Flexible and good for general timing.
  • datetime: Useful for human-readable timestamps.

Using timeit Module

The timeit module is designed to provide precise timings by:

  • Disabling garbage collection temporarily.
  • Repeating execution multiple times for consistency.

Example 1: Basic Usage of timeit.timeit()

In this example, we will analyze how to use the timeit module and use it to find the execution time of a lambda expression.

Python
import timeit  exec_time = timeit.timeit("print('Hello World!')", number=5) print(exec_time, "secs") 

Output
Hello World! Hello World! Hello World! Hello World! Hello World! 8.779999916441739e-06 secs 

Explanation:

  • timeit.timeit(stmt, number): Executes stmt ( statement as a string) number times and returns total time in seconds.
  • Default number of execution is 1_000_000.

Example 2: Measuring a Code Block

In this example, we'll write a Python code segment having a function and it's call as a string and pass it to timeit.timeit() function.

Python
import timeit  code = '''\ import random def run(n):     return n**n run(random.randint(20, 50)) '''  exec_time = timeit.timeit(code, number=10**6) print(f"{exec_time:.3f} secs") 

Output:

3.692 secs

Explanation:

  • Use this format for multi-line code or code requiring imports.
  • Pass the entire block as a string.

Example 3: Repeating Timing with timeit.repeat()

Instead of using timeit.timeit(), we can use timeit.repeat() to run the same code multiple times automatically. It repeats the test and returns a list of results, making it easier to analyze average or consistent execution time without writing extra loops.

Python
import timeit  def square(n):     return n ** 2  times = timeit.repeat(lambda: square(3), number=10, repeat=5)  for i, t in enumerate(times, 1):     print(f"Run {i}: {round(t * 1e6, 2)} µs") 

Output
Run 1: 4.16 µs Run 2: 2.04 µs Run 3: 1.97 µs Run 4: 1.68 µs Run 5: 1.47 µs 

Explanation:

  • timeit.repeat(): Returns a list of timing results.
  • Helps analyze performance over multiple runs.

Example 4: Using timeit.default_timer()

timeit.default_timer() uses the timeit.perf_counter() to record the timestamp of an instance in nanoseconds and we can subtract end time from start time to get the execution time duration in nanoseconds.

Python
import timeit  def square(n):     return n ** 2  s = timeit.default_timer() square(11111111) e = timeit.default_timer()  print(f"Elapsed: {round((e - s) * 1e6, 3)} µs") 

Output
Elapsed: 1.263 µs 

Explanation:

  • default_timer() uses perf_counter() under the hood.
  • Gives high-resolution timestamps.

Using time Module

In Python time module, there are different methods to record and find the execution time of a given code segment. It provides functions like

  • perf_counter()
  • time_ns()
  • process_time()

Example 1: time.perf_counter()

time.perf_counter() method records the time in seconds time unit. Since our sample function is very simple, so, we need to convert it to micro seconds to get time difference value in readable format.

Python
import time  def square(n):     return n ** 2  start = time.perf_counter() square(3) end = time.perf_counter()  print(f"Elapsed: {(end - start) * 1e6:.3f} µs") 

Output
Elapsed: 1.549 µs 

Explanation:

  • time.perf_counter() provides the highest available resolution timer in Python, ideal for measuring short durations.
  • we capture the start time before running the function and end time after.
  • elapsed time is then calculated in microseconds for readability.

Example 2: time.time_ns() (Nanosecond Precision)

To measure the elapsed time or execution time of a block of code in nanoseconds, we can use the time.time_ns() function.

Python
import time  def square(x):     return x ** 2  start = time.time_ns() square(3) end = time.time_ns()  print("Time taken", end - start, "ns") 

Output
Time taken 1504 ns 

Explanation:

  • time.time_ns() is similar to time.time() but returns time in nanoseconds.
  • It’s suitable when we need very high precision, like benchmarking ultra-fast code.

Example 3: time.process_time() (CPU Time)

time.process_time() function returns the sum of the system and the user CPU time.

Python
import time  def heavy_calc(n):     return n ** 76567  start = time.process_time() heavy_calc(125) end = time.process_time()  print("CPU Time:", (end - start) * 1e3, "ms") 

Output
CPU Time: 21.163569 ms 

Explanation:

  • process_time(): Measures CPU time, ignores sleep and I/O delays.
  • Good for profiling CPU-bound tasks.

Using datetime Module

Use datetime when human-readable timestamps are preferred.

Example: datetime.now()

Python
from datetime import datetime  def square(n):     return n ** 2  s = datetime.now() square(3) e = datetime.now()  elapsed = (e - s).total_seconds() * 1e6 print("Elapsed:", elapsed, "µs") 

Output
Elapsed: 10.0 µs 

Also read: timeit.repeat(), time.process_time().


Next Article
How to add time delay in Python?
author
saikatsahana91
Improve
Article Tags :
  • Python
  • Python-datetime
  • Python time-module
Practice Tags :
  • python

Similar Reads

  • How to Measure Elapsed Time in C++?
    Measuring elapsed time is a common requirement for most software development packages. It is used to determine the efficiency of the program and gives an idea of which parts of the program takes which much time. This helps in optimizing the code, such that improves its execution time. In this articl
    3 min read
  • How to add time delay in Python?
    In this article, we are going to discuss how to add delay in Python.  How to add Time Delay?In order to add time delay in our program code, we use the sleep() function from the time module. This is the in-built module in Python we don't need to install externally.Time delay means we are adding delay
    5 min read
  • How to Measure Script Execution Time in PHP?
    Measuring the script execution time in PHP is the time required to execute the PHP script. To calculate script execution time use clock time rather than the CPU execution time. Measuring script execution time is useful to check and improve the execution time for better application performance. Measu
    2 min read
  • How to Measure Execution Time of Function in R ?
    In this article, we will learn how to measure the execution or running time of a function in the R programming language.  Method 1: Using Sys.time For this first create a sample function that runs for a specific duration. For doing so pass the duration to Sys.sleep() function. Syntax:    startTime
    4 min read
  • How to set an input time limit in Python?
    In this article, we will explain how to set an input time limit in Python. It is one of the easiest programming languages which is not only dynamically typed but also garbage collected. Here we will look at different methods to set an input time limit. Below are the methods we will use in this artic
    6 min read
  • How to capture SIGINT in Python?
    The signal module performs a specific action on receiving signals. Even it has the ability to capture the interruption performed by the user through the keyboard by use of SIGINT. This article will discuss SIGINT only, how to capture it, and what to do after it has been captured. Modules Required: S
    3 min read
  • How to Minimize Python Script Execution Time?
    Minimizing Python script execution time is essential for improving performance, especially in production environments, competitive programming (CP) or data structures and algorithms (DSA). Faster execution ensures better user experience in apps and helps us perform well in coding challenges. In this
    3 min read
  • Timeit in Python with Examples
    The timeit module in Python accurately measures the execution time of small code snippets, offering more consistent results than time.time() by avoiding background interference and disabling garbage collection. It’s ideal for comparing code performance, benchmarking and optimization and can be used
    3 min read
  • Python | time.time_ns() method
    Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method. The epoch
    2 min read
  • Python | time.process_time_ns() method
    Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. time.process_time_ns() method of time module in Python is used to get the sum of the system and user CPU time of the current process in nanoseconds. This method does not include
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences