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:
Running Python program in the background
Next article icon

Measure time taken by program to execute in Python

Last Updated : 02 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Measuring the execution time of a Python program is useful for performance analysis, benchmarking, and optimization. Python provides several built-in modules to achieve this with ease. In this article, we’ll explore different ways to measure how long a Python program takes to run.

Using the time Module

The time module provides a simple way to measure execution time by capturing timestamps before and after the code runs using time.time(). It returns the time in seconds since the epoch.

Python
import time  start = time.time()  for i in range(5):     print("GeeksForGeeks")  time.sleep(1) end = time.time()  print(f"Total runtime of the program is {end - start} seconds") 

Output
GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks Total runtime of the program is 1.0009586811065674

Explanation:

  • start stores the time before the loop starts and end captures the time after execution .
  • loop prints a string 5 times.
  • time.sleep(1) adds a 1-second pause to simulate delay.
  • total runtime is printed as the difference between end and start.

Using the timeit Module

timeit module is specifically designed to measure the execution time of small code snippets with high precision. It avoids many common timing pitfalls.

Python
import timeit  s = "from math import sqrt"  t = ''' def example():     mylist = []     for x in range(100):         mylist.append(sqrt(x)) example() '''  print(timeit.timeit(setup=s, stmt=t, number=10000)) 

Output
0.08390588600002502 

Explanation:

  • s runs once to import necessary functions.
  • t defines a small function that computes square roots.
  • timeit.timeit() executes the code 10,000 times and returns the total time taken.

Using default_timer() from timeit

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):     s = "GeeksForGeeks"  end = timer()  print(end - start) 

Output
6.883998139528558e-06 

Explanation:

  • timer() records high-precision start and end times.
  • A loop runs 100 times with a basic assignment inside.
  • The duration is printed as the difference between end and start.

Using the datetime Module

datetime module provides utilities to work with date and time. Using datetime.now() before and after execution allows you to measure duration in a readable format.

Python
import datetime  start = datetime.datetime.now()  for _ in range(10_000_000):     statement = "GeeksForGeeks"  end = datetime.datetime.now()  print(end - start) 

Output
0:00:00.588817

Explanation:

  • start stores the current timestamp before the loop and end captures the time after execution.
  • The loop performs a basic string assignment 10 million times.
  • The duration is printed as a timedelta object.

Note: Output will vary depending on your system speed and CPU load.

Related articles:

  • default_timer method()
  • timeit module
  • time module


Next Article
Running Python program in the background

D

divyamohan123
Improve
Article Tags :
  • Python
  • Python Programs
  • python-utility
Practice Tags :
  • python

Similar Reads

  • Understanding the Execution of Python Program
    This article aims at providing a detailed insight into the execution of the Python program. Let's consider the below example. Example: C/C++ Code a = 10 b = 10 print("Sum ", (a+b)) Output: Sum 20 Suppose the above python program is saved as first.py. Here first is the name and .py is the e
    2 min read
  • How to make a Python program wait?
    The goal is to make a Python program pause or wait for a specified amount of time during its execution. For example, you might want to print a message, but only after a 3-second delay. This delay could be useful in scenarios where you need to allow time for other processes or events to occur before
    2 min read
  • Running Python program in the background
    Let us see how to run a Python program or project in the background i.e. the program will start running from the moment device is on and stop at shut down or when you close it. Just run one time to assure the program is error-bug free One way is to use pythonw, pythonw is the concatenation of python
    3 min read
  • Python Program to Find Area of a Circle
    The task of calculating the Area of a Circle in Python involves taking the radius as input, applying the mathematical formula for the area of a circle and displaying the result. Area of a circle formula: Area = pi * r2where π (pi) is a mathematical constant approximately equal to 3.14159. r is the r
    3 min read
  • Python for Kids - Fun Tutorial to Learn Python Programming
    Python for Kids - Python is an easy-to-understand and good-to-start programming language. In this Python tutorial for kids or beginners, you will learn Python and know why it is a perfect fit for kids to start. Whether the child is interested in building simple games, creating art, or solving puzzle
    15+ min read
  • Python Tutorial | Learn Python Programming Language
    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
    10 min read
  • Python List Counting Programs
    Python provides various methods, such as count(), dictionary-based counting, and list comprehensions, to efficiently handle counting operations. This collection of Python programs covers different ways to count elements in lists, including counting occurrences, matching elements, frequency analysis,
    2 min read
  • Output of Python Program | Set 1
    Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of
    3 min read
  • Output of Python program | Set 5
    Predict the output of the following programs: Program 1: [GFGTABS] Python def gfgFunction(): "Geeksforgeeks is cool website for boosting up technical skills" return 1 print (gfgFunction.__doc__[17:21]) [/GFGTABS]Output: coolExplanation: There is a docstring defined for this method,
    3 min read
  • Measure The Time You Take To Type A Word Using Python
    Here, we have task to measure the time takes to type a word in Python. In this article we will see how to measure the time you to type a word in Python, we will type the word and measure the type using some simple generally used methods. Example : Input : Type the word 'GeeksforGeeks': GeeksforGeeks
    3 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