0

Why doesn't it just take the same amount of time? Does it have something to do with other programs, background processes etc?

import time

def calcProd():
        'Calculates the product of numbers from 1 through 100,000'
        product = 1

    for x in range(1, 100000):
        product *= x

    return product

start = time.time()
calcProd()
end = time.time()

elapsed = round((end - start), 7)

print(elapsed)

and the times(in seconds) tested are as follows:

  1. 24.1244698

  2. 22.9401324

  3. 23.3407295

  4. 23.2885954

  5. 23.3982868

  6. 21.177716

I know this is may seem to be a trivial question, but bear with me. And is there a more efficient way to perform the same function? Thanks

*The primary part of this question was to spark discussion as to why the times vary so much when running the same program over and over. The last part was more of just a spontaneous question.

Rene
  • 370
  • 3
  • 14
  • Yes, your program is not the only thing running on your computer. The deltas are around 10% hardly varying 'wildly'. You can see some faster factorial algos here https://web-beta.archive.org/web/20110727052531/http://en.literateprograms.org/Factorials_with_prime_factorization_(Python) – pvg Dec 17 '16 at 23:03
  • *is there a more efficient way to perform the same function?* Yes, `math.factorial()`. – Martijn Pieters Dec 17 '16 at 23:04

0 Answers0