i am new to programming, please tell me, why when im executing my code the timer is literally in the stratosphere?

Question:

from multiprocessing import Process, cpu_count
import time

def counter(num):

    count = 0
    while count < num:
        count += 1

def main():

    a = Process(target=counter, args=(1000000000,))
    a.start()
    
    a.join()
    
    print('finished in: ', time.perf_counter(), 'seconds')

if __name__ == '__main__':
    main()

was expecting to work properly, but when i do it my timer goes like this: 692018.2843528 seconds

Asked By: nasa28

||

Answers:

From the documentation:

time.perf_counter() → float

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.

Call perf_counter before your process starts, again after it completes, and take the difference between the two calls. That is, you can’t assume that your timer "starts" at 0.

Answered By: chepner
from multiprocessing import Process, cpu_count
import time

def counter(num):

    count = 0
    while count < num:
        count += 1

def main():

    # Added this
    start = time.perf_counter()

    a = Process(target=counter, args=(1000000000,))
    a.start()
    
    a.join()
    
    print('finished in: ', time.perf_counter()-start, 'seconds')

if __name__ == '__main__':
    main()

This should be what you want if I understand you correctly 🙂

Answered By: 3m1l
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.