Таймер выполнения программы python

Create a Timer in Python: Step-by-Step Guide

Time tracking is critical to managing your projects. If you’re programming in Python, you’re in luck: The language gives you tools to build your own timers. A timer program can be useful for not only monitoring your own time, but measuring how long your Python program takes to run.

In this article, we’ll present two simple Python timers before looking at the modules you’ll need to create a timer program. We’ll then use these modules to build a stopwatch and a countdown timer, and show you how to measure a Python program’s execution time.

Understanding Timers in Python

A timer in Python is a time-tracking program. Python developers can create timers with the help of Python’s time modules. There are two basic types of timers: timers that count up and those that count down.

Stopwatches

Timers that count up from zero are frequently called stopwatches. We can use these to record the amount of time it takes to complete a task.

Runners often use stopwatch timers to record how long it takes them to complete a lap around a course or finish an entire run. You can use a stopwatch to track how long it takes to complete any task, such as coding a simple program.

Programmers often use stopwatch timers to compare the performance of various Python solutions. By seeing how long each solution takes to execute, you can choose the program that runs the fastest. Over time, this will allow you to better understand computational complexity and build intuition for choosing efficient solutions. These skills go a long way towards becoming a proficient programmer.

Читайте также:  Hover effect with html

Countdown Timers

There are also countdown timers, set with a specific amount of time that depletes until the timer reaches zero. You can use Python to build countdown timers that serve different purposes.

For instance, you can build a cooking countdown timer to ensure you don’t leave food in the oven for too long. Countdown timers can also work to display the time remaining in a sporting event or during an exam. They are also used to count down the hours and minutes to a movie release or big event. The possibilities are endless!

Modules in Python

To create a simple timer in Python, you’ll need to call upon Python’s time and datetime modules.

Modules in Python are files that contain classes, functions, variables, and runnable code. By importing a module into your program, you can make use of each component inside the module.

The Python programming language has over 200 predefined modules within its standard library. You can even create your own modules to use in future programs.

The Python Time Module

One of the 200 modules in Python’s standard library is the time module. This module contains the functions we’ll need to build a simple timer in Python.

To use the time module in Python, we first import it into our program:

Listing modules at the beginning of a Python program makes the functions within the module available for use in our program. The time module holds more functions than we’ll cover here, but here are the most important ones:

The time.time() function

We call the time() function, located in the time module, as time.time() . The first time references the module, whereas the second is the function itself. The time() function returns the number of seconds that have passed since the epoch.

In the computing context, we refer to an “epoch” as the time according to which a computer calculates its timestamp values. Windows and most UNIX devices set the epoch as January 1, 1970 at 00:00:00.

When we use time.time() , we can see the amount of time that has passed since the epoch. We can even use time.ctime() to convert this number of seconds to the current local time. Take a look at this example:

import time seconds = time.time() print("Time in seconds since the epoch:", seconds) local_time = time.ctime(seconds) print("Local time:", local_time)

In this example, we use time.time() to see how many seconds have elapsed since the epoch. We then convert this length of time to our current local time with time.ctime() . This program outputs the following information:

Time in seconds since the epoch: 1630593076.1314547 Local time: Thu Sep 2 10:31:16 2021

It has been over 1.5 billion seconds since the epoch.

The time.sleep() Function

The other function that we’ll need to build our timer is time.sleep() . This function creates a delay in a program that we can use to count time. time.sleep() takes a float argument representing the number of seconds that the program will pause for. Plug the example below into your Python integrated development environment (IDE) to see how time.delay() works:

import time print("This is the start of the program.") time.sleep(5) print("This prints five seconds later.")

Since we set time.sleep() to five seconds, the program idles for that length of time between outputs.

The Python Datetime Module

datetime is intended for manipulating dates. We’ll use this module to convert different timestamps into a common format that allows us to compare them.

The datetime.timedelta() Function

We can use timedelta() to express the difference between two dates and/or two times. In the example below, we use timedelta() to show the date one year from now:

import datetime current = datetime.datetime.now() print ("Current date:", str(current)) one_year = current + datetime.timedelta(days = 365) print("The date in one year:", str(one_year))


timedelta() adds 365 days to the current date and outputs the date and time one year from now, down to the microsecond:

Current date: 2021-09-02 14:44:19.429447 The date in one year: 2022-09-02 14:44:19.429447

A Simple Lap Timer (Stopwatch)

Let’s use what we’ve learned to build a stopwatch. Our stopwatch is a lap timer that displays the time to complete a lap as well as total time. Check out the code below:

import time # Timer starts starttime = time.time() lasttime = starttime lapnum = 1 value = "" print("Press ENTER for each lap.\nType Q and press ENTER to stop.") while value.lower() != "q": # Input for the ENTER key press value = input() # The current lap-time laptime = round((time.time() - lasttime), 2) # Total time elapsed since the timer started totaltime = round((time.time() - starttime), 2) # Printing the lap number, lap-time, and total time print("Lap No. "+str(lapnum)) print("Total Time: "+str(totaltime)) print("Lap Time: "+str(laptime)) print("*"*20) # Updating the previous total time and lap number lasttime = time.time() lapnum += 1 print("Exercise complete!")

After importing the time module, we set time.time() to the start time of our timer. The stopwatch will count forward from this time. We use the variable lasttime to catalog each lap, whereas totaltime holds the value for the entire time the stopwatch runs. lapnum counts the number of laps we run. Finally, we set the value variable so the user can type “Q” or “q” to end the program.

Time increments in the background while we run the program. Each time the user presses the Enter key, the program displays their lap number, lap time, and total time. Even if you don’t need to record laps, you can still use this timer to track the total time you’re performing a task.

A Simple Countdown Timer

Let’s now build a countdown timer. This example incorporates both the datetime module and the time.sleep() function. Take a look at the program below:

import time import datetime # Create class that acts as a countdown def countdown(h, m, s): # Calculate the total number of seconds total_seconds = h * 3600 + m * 60 + s # While loop that checks if total_seconds reaches zero # If not zero, decrement total time by one second while total_seconds > 0: # Timer represents time left on countdown timer = datetime.timedelta(seconds = total_seconds) # Prints the time left on the timer print(timer, end="\r") # Delays the program one second time.sleep(1) # Reduces total time by one second total_seconds -= 1 print("Bzzzt! The countdown is at zero seconds!") # Inputs for hours, minutes, seconds on timer h = input("Enter the time in hours: ") m = input("Enter the time in minutes: ") s = input("Enter the time in seconds: ") countdown(int(h), int(m), int(s))

Our countdown timer works by having a user input the number of hours, minutes, and seconds for the timer. You can find the code for these inputs at the bottom of the program below the countdown class.

The countdown class itself takes those inputs and converts them into a total number of seconds. As long as total_seconds is greater than zero, the while loop runs. Within the loop, we use the timedelta() function to calculate the time left on the timer.

The program prints the time left in hours:minutes:seconds format for the user to see. Immediately after, the program pauses for one second, reduces total_seconds by one second, and repeats the while loop. The loop continues until total_seconds reaches zero, at which point the program leaves the while loop and prints “Bzzzt! The countdown is at zero seconds!”

Measure Program Execution Time

You can use Python to measure the time it takes for a program to finish execution. This is not very different from what we’ve already done before: We define a starting point, run the program whose time we want to measure, and specify the time at which the program finishes execution. We get the program’s execution time by subtracting the start time point from the end time point.

Let’s compare a few solutions for finding an element within a list. We’ll create a list of 10,000,000 elements and see how long it takes each solution to find the number 700,000.

First, we’ll build a program that makes random guesses until it finds the answer.

v​​import time import random our_list = list(range(10000000)) element = 7000000 start = time.time() random_choice = random.choice(our_list) while random_choice != element: random_choice = random.choice(our_list) end = time.time() print(end - start)

The program took 16 seconds to find the element; that’s clearly no good.

Let’s try a better approach. This time, instead of making random guesses, the program will make one pass through the list to look for the element.

import time our_list = list(range(10000000)) element = 7000000 start = time.time() for el in our_list: if el == element: break end = time.time() print(end - start)

This program took only 0.6 seconds. That’s a lot better.

Let’s see if we can beat this time with a more sophisticated algorithm called “binary search.” We borrow the code for the algorithm from this GitHub page.

import time our_list = list(range(10000000)) element = 700000 start = time.time() binary_search(our_list, element) end = time.time() print(end - start)

With only 0.1 seconds required to find the element, we’ve found the winning solution!

These examples show the importance of time-tracking if you’re looking to build scalable programs. When you build a program that ends up being used by many people, every fraction of a second saved on computation time helps.

Start Your Python Journey With Udacity

In this article, we explored the time and datetime modules to understand how time works in Python. We used this knowledge to create a lap timer, a countdown timer, and showed you how to measure the execution time of Python programs.

Want to go beyond building timers and dive into fields like app development, machine learning, and data science?

Take your first step by enrolling in Udacity’s Introduction to Programming Nanodegree.

Источник

Оцените статью