multithreading in python and time module

Viewed 31

I'm trying to learn multi_threading in python but when I try to print time.perf_counter() in order to see how much time the Main Threading takes to run the program which is in charge the output is a huge number (614691.9609577), but it should not even be 2 seconds. Can you explain the reason of this problem? Thanks

import threading
import time
    
def have_breakfast():
    time.sleep(3)
    print("You had breakfast")
def make_bed():
    time.sleep(4)
    print("You made your bed")
def study():
    time.sleep(5)
    print("You finish studying")
    
x = threading.Thread(target = have_breakfast, args = ())
x.start()
    
y = threading.Thread(target = make_bed, args = ())
y.start()
    
z = threading.Thread(target = study, args = ())
z.start()
    
x.join()
    
print(threading.active_count())
print(threading.enumerate())
print(time.perf_counter()) 
1 Answers

From here:

time.perf_counter(): Return 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. The reference point of the returned value is undefined, so that only the difference between the results of two calls is valid.

Use perf_counter_ns() to avoid the precision loss caused by the float type.

New in version 3.3.

Changed in version 3.10: On Windows, the function is now system-wide.

In your case if you want to measure time you need to subtract two time intervals. E.g.:

t1_start = time.perf_counter()
# your code...
t2_stop = time.perf_counter()
print("Elapsed time: ", t2_stop - t1_start)
Related