在Python中运行循环需要多长时间?

2024-10-01 15:49:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个程序,它运行的时间相当于用户经常运行的时间(这是一个测试版的空闲游戏)。我在计时器上放了一分钟,注意到程序在一分钟内运行了几秒钟——不是很明显,但我想知道这是否是因为循环执行所需的时间?这是我的代码:

import time

foreverloop = True
automodeOn = False

idleSec = 0
idleMin = 0

pages = 0
pps = 0

while foreverloop:
    if automodeOn == False:
        msg = input("BTCG Command >> ")
        if msg == 'auto':
            autotime = input("How long would you like to go idle for? Answer in minutes.")
            automodeOn = True
        elif msg == 'autoMORE':
            pps += .5
    else:
        pages += pps
        print("You have auto-read",pps,"pages.")
        idleSec += 1
        if idleSec == 60:
            idleSec = 0
            idleMin += 1
        if idleMin == int(autotime):
            print("Idle mode turning off.")
            automodeOn = False
        time.sleep(1)


Tags: 程序falsetrueautoinputiftime时间
2条回答

您可以通过测量开始时间来测量执行多行代码所需的时间:

start = time.time()

在要测量时间的任何行数之前,然后在末尾添加:

end = time.time()

然后将时间流逝计算为它们的减法:

elapsed_time = end-start

我建议您阅读有关代码复杂性的内容,其中最流行的是大O表示法

编辑:如注释中所示,timeit是更好的选择,如果您希望精确地测量某一行或函数执行所需的时间,这两种方法之间的主要区别在于timeit是专门为执行此目的而设置的,并且作为参数的一部分,变量number指示在确定平均运行时间之前运行指定代码的次数

我将使用time.time()以秒为单位获取系统的当前UNIX time作为浮点数,而不是让程序等待执行所需的时间,并且仅在经过特定时间后才继续:

import time

time_begin = time.time()
wait_time = 60 # seconds to wait

while time.time() < time_begin + wait_time:
    # do logic
    print("Time passed:", time.time() - time_begin)
    time.sleep(1) # can be whatever

print(wait_time, "seconds has passed!")

相关问题 更多 >

    热门问题