-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?

19
  • a+b is happening too fast to have any resolution when time() - start is computed. Commented Sep 10, 2021 at 18:58
  • Can you suggest how I can achieve the output as shown in the tutorial in order to demonstrate this to students, or a better way perhaps that demonstrates Commented Sep 10, 2021 at 18:59
  • 1
    Use something more complex than a+b. Commented Sep 10, 2021 at 19:00
  • time.sleep(1) will create output that is ~1 Commented Sep 10, 2021 at 19:00
  • 2
    If you want to demonstrate time complexity, do something whose time is dependent on trial Commented Sep 10, 2021 at 19:01

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.