简体   繁体   中英

my timer seems very off - how do i fix it / what am i doing wrong?

import math
import random
import time

stress_base = 3
stress_report = 0

i = 0


while True:
    start = time.time()
    a = random.randrange(0,9)
    stress_base = stress_base + a
    stress_report = stress_report + 1
    if stress_report % 10000000 == 0:
        time.sleep(.0001)
        end = time.time()
        print((end - start) -.0001,'=',i)
        i = i + 1

this code is a simple benchmark on a system. (I know that even if I fix it won't be useful, its an exercise) the result is how long it takes to add up a million random numbers from 0-9, and the timer for some reason seems completely off, am I missing something?

here are some results

0.0018946098327636718 = 0
0.0018938945770263671 = 1
0.002891914749145508 = 2
0.0018953250885009765 = 3
0.0018936561584472656 = 4
0.0018948482513427734 = 5
0.012865679168701172 = 6
0.0008999275207519531 = 7
0.001895086669921875 = 8
0.0018958019256591796 = 9

the time between each one is roughly half a second. when I increase the number of equations these times don't increase.

Your start variable should be outside of the loop, because currently the value is to add the last random number rather than adding all the random numbers. Also, your modulo was set to check for 10,000,000 when it should be 1,000,000. Correcting this, the variability is between 1.3-1.6 seconds. I also changed the value of i to represent how many million numbers have been added. Here is the code:

import math
import random
import time

stress_base = 3
stress_report = 0

i = 1

while True:
    start = time.time()
    while True:
        a = random.randrange(0,9)
        stress_base = stress_base + a
        stress_report = stress_report + 1
        if stress_report % 1000000 == 0:
            time.sleep(.0001)
            break
    end = time.time()
    print((end - start) -.0001,'=',i)
    i = i + 1

Here is a part of the output:

1.6038764881134033 = 1
1.5193711685180664 = 2
1.4884077476501465 = 3
1.4721638130187988 = 4
1.5818635391235352 = 5
1.4038864540100098 = 6
1.4031793045043945 = 7
1.3717972206115723 = 8
1.472563164138794 = 9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM