0

What I am trying to do is run this program, get the execution time of it, and then continue to do that 9 more times. How would I go about iterating over it to get it to print out 10 different execution times? I'm not quite sure how I need to structure the program in order to accomplish this.

import time
start_time = time.time()


def fibonacci():
    previous_num, result = 0, 1
    user = 1000
    iteration = 10
    while len(str(result)) < user:
        previous_num, result = result, previous_num + result
        while iteration != 0:
            iteration -= 1
            end = time.time()
            print(start_time - end)
    return result


print(fibonacci())
print("--- %s seconds ---" % (time.time() - start_time))
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • you could think about using timeit module if you don't need every execution time and only care about an average time – user1558604 Dec 19 '19 at 16:57
  • Note that there are handy timer decorators such as @timeit (https://stackoverflow.com/questions/1622943/timeit-versus-timing-decorator) – jarmod Dec 19 '19 at 16:58
  • Does this answer your question? [Measure time elapsed in Python](https://stackoverflow.com/questions/7370801/measure-time-elapsed-in-python) – wwii Dec 19 '19 at 18:04
  • Or this one? [Repeating a function a set amount of times in python](https://stackoverflow.com/questions/24570393/repeating-a-function-a-set-amount-of-times-in-python) – wwii Dec 19 '19 at 18:07
  • @wwii Those helped slightly, could you please explain or help me understand better why I would want to use timeit rather than a different module/decorator? – Tyler Heist Dec 20 '19 at 00:43

1 Answers1

1

All you need to do is create a for loop and put your code in it.

import time

def fibonacci(start_time):
    previous_num, result = 0, 1
    user = 1000
    iteration = 10
    while len(str(result)) < user:
        previous_num, result = result, previous_num + result
        while iteration != 0:
            iteration -= 1
            end = time.time()
            print(start_time - end)
    return result

for i in range(0, 10):
    start_time = time.time()
    print(fibonacci(start_time))
    print("--- %s seconds ---" % (time.time() - start_time))
Kim Souza
  • 162
  • 11