-3

I have the following python code:

from time import time


def program1(a,b):
    for trial in range(5):
        start = time()
        a + b
        print (time() - start)
program1(27,59)

and according to the tutorial should produce this output:

9.53674316406e-07
2.14576721191e-06
2.14576721191e-06
3.09944152832e-06
9.53674316406e-07

Instead it produces:

0.0
0.0
0.0
0.0
0.0
>>> 

I am trying to use it demonstrate the concept of time/space complexity.

Can anyone shed any light on the output and why it is not accepting the parameters?

Compoot
  • 2,227
  • 6
  • 31
  • 63

1 Answers1

0

Try this:

from time import time, sleep
import random


def program1(a,b):
    for trial in range(5):
        start = time() # gets current time

        time_to_sleep = random.random() # random() returns a number between 0 and 1
        
        # sleep will block the execution here for the number of seconds passed (0.5 is half a second for instance).
        sleep(time_to_sleep) 
        print (time() - start)
program1(27,59)

I added the random to make it a little bit unpredictable.

Rafael Barros
  • 2,738
  • 1
  • 21
  • 28
  • Rafael - will try - could you add some comments (for teaching purposes). Explaining what is happening. For instance, what exactly is time() doing (calling what). and the sleep.random – Compoot Sep 10 '21 at 19:06