Python get elapsed time

How to Get time of a Python program’s execution

In this article, we will learn to calculate the time taken by a program to execute in Python. We will use some built-in functions with some custom codes as well. Let’s first have a quick look over how the program’s execution affects the time in Python.

Programmers must have often suffered from «Time Limit Exceeded» error while building program scripts. In order to resolve this issue, we must optimize our programs to perform better. For that, we might need to know how much time the program is taking for its execution. Let us discuss different functions supported by Python to calculate the running time of a program in python.

The time of a Python program’s execution measure could be inconsistent depending on the following factors:

  1. The same program can be evaluated using different algorithms
  2. Running time varies between algorithms
  3. Running time varies between implementations
  4. Running time varies between computers
  5. Running time is not predictable based on small inputs

Calculate Execution Time using time() Function

We calculate the execution time of the program using time.time() function. It imports the time module which can be used to get the current time. The below example stores the starting time before the for loop executes, then it stores the ending time after the print line executes. The difference between the ending time and starting time will be the running time of the program. time.time() function is best used on *nix.

import time #starting time start = time.time() for i in range(3): print("Hello") # end time end = time.time() # total time taken print("Execution time of the program is- ", end-start)

Hello
Hello
Hello
Execution time of the program is- 1.430511474609375e-05

Calculate execution time using timeit() function

We calculate the execution time of the program using timeit() function. It imports the timeit module. The result is the execution time in seconds. This assumes that your program takes at least a tenth of a second to run.

The below example creates a variable and wraps the entire code including imports inside triple quotes. The test code acts as a string. Now, we call the time.timeit() function. The timeit() function accepts the test code as an argument, executes it, and records the execution time. The value of the number argument is set to 100 cycles.

import timeit test_code = """ a = range(100000) b = [] for i in a: b.append(i+2) """ total_time = timeit.timeit(test_code, number=200) print("Execution time of the program is-", total_time)

Execution time of the program is- 4.26646219700342

Читайте также:  Java 64 bit microsoft

Calculate execution time using time.clock() Function

Another function of the time module to measure the time of a program’s execution is time.clock() function. time.clock() measures CPU time on Unix systems, not wall time. This function is mainly used for benchmarking purposes or timing algorithms. time.clock() may return slightly better accuracy than time.time() . It returns the processor time, which allows us to calculate only the time used by this process. It is best used on Windows.

import time t0= time.clock() print("Hello") t1 = time.clock() - t0 print("Time elapsed: ", t1 - t0) # CPU seconds elapsed (floating point)

Hello
Time elapsed: -0.02442

Note:

time.clock() is «Deprecated since version 3.3». The behavior of this function depends on the platform. Instead, we can use perf_counter() or process_time() depending on the requirements or have a well-defined behavior.

time.perf_counter() — It returns the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide.

time.process_time() — It returns the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep. For example,

start = time.process_time() . do something elapsed = (time.process_time() - start)

Calculate execution time using datetime.now() Function

We calculate the elapsed time using datetime.datetime.now() from the datetime module available in Python. It does not make the script a multi-line string like in timeit() . This solution is slower than the timeit() since calculating the difference in time is included in the execution time. The output is represented as days, hours, minutes, etc

The below example saves the current time before any execution in a variable. Then call datetime.datetime.now() after the program execution to find the difference between the end and start time of execution.

import datetime start = datetime.datetime.now() list1 = [4, 2, 3, 1, 5] list1.sort() end = datetime.datetime.now() print(end-start)

Calculate execution time using %%time

We use %%time command to calculate the time elapsed by the program. This command is basically for the users who are working on Jupyter Notebook. This will only capture the wall time of a particular cell.

%%time [ x**2 for x in range(10000)]

Why is timeit() the best way to measure the execution time of Python code?

1. You can also use time.clock() on Windows and time.time() on Mac or Linux. However, timeit() will automatically use either time.clock() or time.time() in the background depending on the operating system.

2. timeit() disables the garbage collector which could otherwise skew the results.

3. timeit() repeats the test many times to minimize the influence of other tasks running on your operating system.

Conclusion

In this article, we learned to calculate the time of execution of any program by using functions such as time() , clock() , timeit() , %%time etc. We also discussed the optimization of the python script. We learned about various functions and their uniqueness.

Источник

Get Elapsed Time in Seconds in Python

To measure the elapsed time of a process in Python, use the time module to find the starting time and ending time, and then subtract the two times.

import time starting_time = time.time() print("Process started. ") print("Process ended. ") ending_time = time.time() print(ending_time - starting_time) #Output: 0.0018320083618164062

When creating Python programs, the ability to easily benchmark and calculate the elapsed time of a program can be very useful.

Читайте также:  Java util collection методы

You can easily calculate the elapsed time of a piece of Python code with the help of the time module.

The time() function from the time module gets the current time. We can use time() to get the starting time, the ending time and then take the time difference to get the time elapsed.

Below is a simple example in Python of how to get the elapsed time in seconds.

import time starting_time = time.time() print("Process started. ") print("Process ended. ") ending_time = time.time() print(ending_time - starting_time) #Output: 0.0018320083618164062

Formatting the Elapsed Time of Program in Python

When subtracting two times in Python, we get the time elapsed in seconds. However, sometimes we want to format the time elapsed so it’s easier to read and understand.

We can use the timedelta() function from the datetime module to create a timedelta object which will format the time elapsed.

When printed to the console, timedelta objects print HH:MM:SS.

Below is how to convert the time elapsed to a timedelta object in Python.

import time from datetime import timedelta starting_time = time.time() print("Process started. ") print("Process ended. ") ending_time = time.time() print(timedelta(seconds=ending_time - starting_time)) #Output: 0:00:00.001832

Hopefully this article has been useful for you to learn how to measure and print the time elapsed in a Python program.

  • 1. Truncate String in Python with String Slicing
  • 2. pandas Absolute Value – Get Absolute Values in a Series or DataFrame
  • 3. How to Filter pandas DataFrame by Date
  • 4. Sort a List of Strings Using Python
  • 5. How to Hide Turtle in Python with hideturtle() Function
  • 6. Remove Leading and Trailing Characters from String with strip() in Python
  • 7. Perform Reverse Dictionary Lookup in Python
  • 8. Get Month Name from Datetime in pandas DataFrame
  • 9. Perfect Numbers in Python
  • 10. Using readlines() and strip() to Remove Spaces and \n from File in Python

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

Calculate Time Elapsed in Python

Calculate Time Elapsed in Python

  1. Calculate Elapsed Time of a Function With time() Function of time Module in Python
  2. Calculate Elapsed Time of a Function With perf_counter() Function of time Module in Python
  3. Calculate Elapsed Time of a Function With process_time() Function of time Module in Python

In this tutorial, we will discuss methods to calculate the execution time of a program in Python.

The time module is a built-in module that contains many time-related functions. Several methods inside the time module can be used to calculate the execution time of a program in Python. These methods are discussed below.

Calculate Elapsed Time of a Function With time() Function of time Module in Python

The time() function gives us the current time in seconds. It returns a float value that contains the current time in seconds. The following code example shows us how we can calculate the execution time of a function with the time() function in Python.

import time  start = time.time()  print("The time used to execute this is given below")  end = time.time()  print(end - start) 
The time used to execute this is given below 0.00011444091796875 

In the above code, we first initialize the start variable that contains the starting time using the time() function and then initialize the end variable after the print() statement using the time() function. We then calculate the total execution time by subtracting the start from the end .

Читайте также:  writing-mode

Calculate Elapsed Time of a Function With perf_counter() Function of time Module in Python

The perf_counter() function gives the most accurate measure of the system time. The perf_counter() function returns system-wide time and takes the sleep time into account. The perf_counter() function can also be used to calculate the execution time of a function. The following code example shows us how we can calculate the execution time of a function with the perf_counter() function in Python.

import time  start = time.perf_counter()  print("This time is being calculated")  end = time.perf_counter()  print(end - start) 
This time is being calculated 0.00013678300001629395 

In the above code, we first initialize the start variable that contains the starting time using the perf_counter() function and then initialize the end variable after the print() statement using the perf_counter() function. We then calculate the total execution time by subtracting the start from the end .

Calculate Elapsed Time of a Function With process_time() Function of time Module in Python

The perf_counter() function is affected by other programs running in the background on the machine. It also counts the sleep time. So, it is not ideal for measuring the execution time of a program.

The best practice for using the perf_counter() function is to run it several times, and then the average time would give a reasonably accurate estimate of the execution time.

Another approach would be to use the process_time() function. The process_time() function is specifically designed to estimate the execution time of a program. It is not affected by other programs running in the background on the machine. It also does not count the sleep time.

The process_time() function returns a float value that contains the sum of the system and the user CPU time of the program. The following code example shows us how we can calculate the execution time of a function with the process_time() function in Python.

import time  start = time.process_time()  print("This time is being calculated")  end = time.process_time()  print(end - start) 
This time is being calculated 0.000991254000000108 

In the above code, we first initialize the start variable that contains the starting time using the process_time() function and then initialize the end variable after the print() statement using the process_time() function. We then calculate the total execution time by subtracting the start from the end .

Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.

Related Article — Python Time

Источник

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