41
loading...
This website collects cookies to deliver better user experience
time.perf_counter()
functiontime.perf_counter()
function# import time module
import time
# start the time and capture it in a variable
start = time.perf_counter()
# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
content = file.read()
print(content)
file.close()
# capture the end time and store it in a variable
end = time.perf_counter()
print('The total time taken to execute code is ', end - start)
Hello
Welcome to Python Tutorial
Cheers
Appending the content
Python
The total time taken to execute code is 0.05468999221
timeit
module is often used to measure the elapsed time of smaller code snippets. We can also use the timeit()
function, which executes the anonymous function with several executions.# import timeit module
import timeit
# start the time and capture it in a variable
start = timeit.default_timer()
# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
content = file.read()
print(content)
file.close()
# capture the end time and store it in a variable
end = timeit.default_timer()
print('The total time taken to execute code is ', end - start)
Hello
Welcome to Python Tutorial
Cheers
Appending the content
Python
The total time taken to execute code is 0.005783799999999999
timeit.timeit()
function can take another function as an argument, and it can execute the method multiple times by specifying the value into the number argument.# import timeit module
from os import read
from time import sleep
import timeit
def readfile():
sleep(2)
# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
content = file.read()
file.close()
return content
t = timeit.timeit(lambda: readfile(), number=10)
print('The total time taken to execute code is ', t)
The total time taken to execute code is 20.1075041
timeit.repeat()
function as shown below.# import timeit module
from os import read
from time import sleep
import timeit
def readfile():
sleep(1)
# Program to read the entire file (absolute path) using read() function
with open("C:/Projects/Tryouts/python.txt", "r") as file:
content = file.read()
file.close()
return content
t = timeit.repeat(lambda: readfile(), number=10, repeat=5)
print('The total time taken to execute code is ', t)
The total time taken to execute code is [10.1566243, 10.102775400000002, 10.128235400000001, 10.065340800000001, 10.076453699999995]