在我的 Python 斐波那契程序中,时间函数似乎总是在增加

Time function seems to always be increasing in my Python Fibonacci program

我正在尝试使用计时器来查看每个功能的速度。我的代码有效,但在 运行 多次使用后,我得到的结果略有不同,想知道我是否正确地实现了功能。我只去第 10 个斐波那契数,即 55 进行测试。每次我 运行 "A" 选项 clockTime() 函数 returns 一个比以前稍大的数字。如有任何想法,我们将不胜感激。

import math
import time

#create a time variable
start_time = time.time()

#create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2

#the runtime function
def clockTime():
    print("\nrun time: " + str(time.time()-start_time))

#the golden ration function
def fibGen(num):
        for number in range(0,num+1):
            val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
            print('{i:3}: {v:3}'.format(i=number, v=round(val)))

#the find element < Max number function
def elemFib(num):
        for number in range(0,num+1):
            val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
            if val < num:
                print('Fib({}): {}'.format(number, round(val)))

#Pythonic way
def pythonic():
    a, b = 0,1
    while a < 57:
        print(a, sep=" ", end="\n")
        a, b = b, a+b

#display the Main Menu
def dispMenu():
    print('---------------------Fibonacci Series ------------------\n')
    print('(A) Print Fibonacci numbers to the nth term')
    print('(B) Print Fibonacci numbers until element is less than Max number')
    print('(C) pythonic print')
    print('(Q) Quit the program\n')


def  main():
          # set boolean control variable for loop
          loop = True

          #Create while loop for menu
          while loop:

              #Display the menu
              dispMenu()

              #Get user's input
              choice = (input('Please make a selection: '))

              #Perform the selected action
              if choice.upper() == 'A':
                  num = int(input("How many Fibonacci numbers should I print? "))
                  fibGen(num)
                  clockTime()
              elif choice.upper() == 'B':
                  num = int(input("the element should be less than? "))
                  elemFib(num)
                  clockTime()
              elif choice.upper() =='C':
                  pythonic()
                  clockTime()
              elif choice.upper() == 'Q':
                  print('\nExiting program, Thank you and Goodbye')
                  loop = False
              else:
                  print('\nInvalid selection, try again\n') 


main()

问题是您 start_time 在程序开始时初始化,而不是在 运行 要计时的函数之前初始化。您添加了以前运行的时间以及用户阅读说明和做出决定所花费的时间等。这是您的代码的返工,应该可以满足您的要求:

import math
import time

# create the golden Ratio formula
golden_ratio = (1 + math.sqrt(5)) / 2

# the runtime function
def clockTime(start_time):
    print("\nrun time:", time.time() - start_time)

# the golden ration function
def fibGen(num):
    for number in range(num+1):
        val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
        print('{i:3}: {v:3}'.format(i=number, v=round(val)))

# the find element < Max number function
def elemFib(num):
    for number in range(num + 1):
        val = (golden_ratio**number - (1 - golden_ratio)**number) / math.sqrt(5)
        if val < num:
            print('Fib({}): {}'.format(number, round(val)))

# Pythonic way
def pythonic():
    a, b = 0, 1

    while a < 57:
        print(a, sep=" ", end="\n")
        a, b = b, a + b

# display the Main Menu
def dispMenu():
    print('---------------------Fibonacci Series ------------------\n')
    print('(A) Print Fibonacci numbers to the nth term')
    print('(B) Print Fibonacci numbers until element is less than Max number')
    print('(C) pythonic print')
    print('(Q) Quit the program\n')

def  main():
    # set boolean control variable for loop
    loop = True

    # Create while loop for menu
    while loop:

        # Display the menu
        dispMenu()

        # Get user's input
        choice = input('Please make a selection: ').upper()

        # Perform the selected action
        if choice == 'A':
            num = int(input("How many Fibonacci numbers should I print? "))
            start_time = time.time()
            fibGen(num)
            clockTime(start_time)
        elif choice == 'B':
            num = int(input("the element should be less than? "))
            start_time = time.time()
            elemFib(num)
            clockTime(start_time)
        elif choice == 'C':
            start_time = time.time()
            pythonic()
            clockTime(start_time)
        elif choice == 'Q':
            print('\nExiting program, Thank you and Goodbye')
            loop = False
        else:
            print('\nInvalid selection, try again\n')

main()