I copied loop function that return value of fibbonacci sequence by inputed index.
Now I'm trying to write function "tester()" that find first index of this sequence whose calculation took the program a certain number of milliseconds and when i input for example 3ms then program calculate everything but in the output shows that the program leasted 0 ms.
def fib_loop(n):
start = int(datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]) #check system time when the function was initialize
n1, n2 = 1, 1
count = 0
if n == 1 or n == 2:
return n1
else:
while count < n-2:
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
stop = int(datetime.now().strftime("%Y%m%d%H%M%S%f")[:-3]) #check system time on the end of the function
time = stop - start #compare times to get the milisecounds of function works
return time
def tester(miliseconds):
x = 0
while True:
if fib_loop(x) <= miliseconds:
x += 1
else:
return x, fib_loop(x)
print(tester(3)) #(2747, 0)
As You see when I input 3 ms as a parameter, the function return around 3000th index of sequence but fib_loop(x) == 0 (fib_loop(x) return how long this function leasted), how it is possible if fib_loop(x) have to be higher than miliseconds to jump into return?
if fib_loop(x) <= miliseconds:
x += 1
else:
return x, fib_loop(x)
PS: When I pass a larger parameter to the function tester(), like 10, it's return +- 7. Can You explaim me why is this happening? Thank you in advance so much, and really sorry for my english.
Is this what you're looking for, I added a function wrapper to time the execution, for more info google 'python decorator':
import time
# wrapper function for decorating fib_loop
def time_func(func):
def wrapper(*args, **kwargs):
start = time.time() * 1000 # unix timestamp
func(*args, **kwargs) # <------- fib_loop here
stop = time.time() * 1000
return stop - start
return wrapper
@time_func # execute fib_loop wrapped in the operations above
def fib_loop(n):
n1, n2 = 1, 1
count = 0
if n == 1 or n == 2:
return n1
else:
while count < n-2:
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
# removed timing from here
def tester(miliseconds):
x = 0
while True:
duration = fib_loop(x)
data = {x: duration} # format the data as a dictionary, just because
if duration <= miliseconds:
print(data)
x += 1
else:
print('')
return data # return the index and duration of the first sequence above the threshold
print(tester(3))