Python,函数跳过条件

Python, function skips condition

我通过输入索引复制了 return 斐波那契数列值的循环函数。

现在我正在尝试编写函数 "tester()" 来查找此序列的第一个索引,该序列的计算花费了程序一定的毫秒数,当我输入例如 3ms 时,程序会计算除输出之外的所有内容显示该程序最少 0 毫秒。

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)

如您所见,当我输入 3 毫秒作为参数时,函数 return 大约是序列的第 3000 个索引,但是 fib_loop(x) == 0 (fib_loop(x) return 这个函数最少多长时间),如果 fib_loop(x) 必须高于毫秒才能跳转到 return?

怎么可能
    if fib_loop(x) <= miliseconds:
        x += 1
    else:
        return x, fib_loop(x)

PS:当我将一个更大的参数传递给函数 tester() 时,例如 10,它是 return +- 7。 你能解释一下为什么会这样吗?非常感谢你,真的很抱歉我的英语。

这是你要找的吗,我添加了一个函数包装器来计时执行,以获取更多信息 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))