【问题标题】:Python execution timePython 执行时间
【发布时间】:2021-05-03 16:51:23
【问题描述】:

有一个关于执行时间的问题(可能我计算错了,即使从我的角度来看它的声音逻辑。在最后一次 for ( 在第一次迭代中(当 i = 0 时)时间是 54 秒 ~ ,下一次迭代我有 161 秒,第三次 257 等等。为什么会这样?时间应该相似吗?谢谢,祝你有美好的一天!

import random
from Decorators.decoratorsExample import *

class BingoCage():
    def __init__(self, items):
        self._items = list(items)
        random.shuffle(self._items)

    def pick(self):
        try:
            return self._items.pop()
        except IndexError:
            return 'No more items in the list'

    def bingo_card(self):
        number = random.sample(self._items, 6) 
        return set(number)
number_of_balls = 49

bingo_round = BingoCage(range(number_of_balls))

print(bingo_round.bingo_card())
Player_with_1_card = bingo_round.bingo_card()


def bingo_check():
    picked_numbers = []
    bingo_round = BingoCage(range(number_of_balls))
    Player_with_1_card = bingo_round.bingo_card()
    for i in range(number_of_balls):
        picked_numbers.append(bingo_round.pick())
        if Player_with_1_card.issubset(picked_numbers):
            # print("BINGO after {0} balls".format(len(picked_numbers)))
            return len(picked_numbers)


record = []


@timer1
def bingo_cycle(number_of_iterations=100000):
    for i in range(number_of_iterations):
        record.append(bingo_check())
        if min(record) == 6:
            break

    print("All the balls were extracted at the minimum of {0} balls after {1} rounds".format(min(record),
                                                                                             number_of_iterations))

for i in range(10):
    bingo_cycle()

【问题讨论】:

  • 什么是Decorators.decoratorsExample?你的计时器是从那里来的吗?
  • 您好,是的 :) 很抱歉,它只是一个基本计时器: def timer1(func): import time def wraper_timer(*args, **kwargs): t1 = time.time() result = func(*args, **kwargs) t2 = time.time() print('{0} 执行时间为 {1} sec'.format(func.__name__,t2 - t1)) 返回结果 return wraper_timer

标签: python python-3.x


【解决方案1】:

函数min(record)的执行时间与record的长度成线性关系。由于您附加到record,因此它的长度会从一次迭代增加到另一次迭代。这也是min 的执行时间增加的原因。

【讨论】:

  • 知道了:),非常感谢,刚刚将它移到了函数中,一切都很好,真不敢相信我把他忘在那里了 :D,祝你有美好的一天!
猜你喜欢
  • 2021-11-17
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 2019-02-07
  • 2018-01-11
  • 2018-02-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多