-1

I'm writing a very simple program to calculate the factorial of a number.

Here it is:

import time
def factorial1(n):
    fattoriale = 1
    while (n > 0):
        fattoriale = fattoriale * n
        n = n - 1
    return fattoriale

start_time = time.clock()
factorial1(v)
print float(time.clock() - start_time), "seconds"

The strange point (for me) are the results in term of execution time (on a value):

1° run: 0.000301 seconds

2° run: 0.000430 seconds

3° run: 0.000278 seconds

Why do you think it's so variable? Does it has something to do with the float type approximation?

Thanks, Gianluca

Gianx
  • 233
  • 3
  • 11

2 Answers2

1

It probably has a lot to do with sharing of resources. If your program runs as a separate process, it might have to contend for other processes running on your computer at the same time which are using resources like CPU and RAM. These resources are used by other processes as well so 'acquire' them in terms of concurrent terms will take variable times especially if there are some high-priority processes running parallel to it and other things like interupts may have higher priority.

As for your idea, from what I know, the approximation process should not take variable times as it runs a deterministic algorithm. However the approximation process again may have to contend for the resources.

damith219
  • 137
  • 11
1

On Unix based systems time.clock returns the CPU time, not the wall-clock time.

Your program is deterministic (even the print is) and on an ideal system should always run in the same amount of time. I believe that in your tests your program was interrupted and some interrupt handler was executed or the scheduler paused your process and gave the CPU to some other process. When your process is allowed to run again the CPU cache might have been filled by the other process, so the processor needs to load your code from memory into the cache again. This takes a small amount of time - which you see in your test.

For a good quantization of how fast your program is you should consider not calling factorial1 only once but thousands of times (or with greater input values). When your program runs for multiple seconds, then scheduling effects have less (relative) impact than in your test where you only tested for less than a millisecond.

Werner Henze
  • 16,404
  • 12
  • 44
  • 69