限制python中每秒的动作数量?

时间:2016-02-16 23:45:28

标签: python python-3.x

我如何通过限制python中的程序每秒执行的操作数量来实现。我知道你可以在每行代码之间加上time.sleep(n),但有更简单的方法吗?

2 个答案:

答案 0 :(得分:0)

听起来这是学习如何使用调试器的好时机。它允许您在代码中的某些点设置断点,并查看在这些点对您很重要的各种值。

它们还可以让您运行快速代码行,以查看它们如何与程序的当前状态进行交互。查看Python的调试器pdb

答案 1 :(得分:0)

在一个百灵鸟上我写了这个:

def slowdown(source,target,n,indent = 4):
    f = open(source)
    lines = f.read().split('\n')
    f.close()
    f = open(target,'w')
    f.write('from time import sleep\n')
    for line in lines:
        f.write(line + '\n')
        if len(line.strip()) > 0:
            level = len(line) - len(line.lstrip())
            if line.strip().endswith(':'):
                level += indent
            f.write(' '*level + 'sleep(' + str(n) + ')\n')
    f.close()
然后我评估了

slowdown('dice.py','slowdice.py',0.5)    

dice.py的样子:

#dice.py

import random

def roll(n):
    return random.randint(1,n)

grand_total = 0
for i in range(100):
    die = roll(6)
    count = 1 # I've already rolled once
    rolls = str(die)

    while die != 6:
        die = roll(6)
        rolls += str(die)
        count +=1

    print(rolls)
    grand_total += count

average = grand_total / 100
print('-'*20)
print("An average of %0.1f rolls required" % average)

它创建以下文件(名为slowdice.py):

from time import sleep
#dice.py
sleep(0.5)

import random
sleep(0.5)

def roll(n):
    sleep(0.5)
    return random.randint(1,n)
    sleep(0.5)

grand_total = 0
sleep(0.5)
for i in range(100):
    sleep(0.5)
    die = roll(6)
    sleep(0.5)
    count = 1 # I've already rolled once
    sleep(0.5)
    rolls = str(die)
    sleep(0.5)

    while die != 6:
        sleep(0.5)
        die = roll(6)
        sleep(0.5)
        rolls += str(die)
        sleep(0.5)
        count +=1
        sleep(0.5)

    print(rolls)
    sleep(0.5)
    grand_total += count
    sleep(0.5)

average = grand_total / 100
sleep(0.5)
print('-'*20)
sleep(0.5)
print("An average of %0.1f rolls required" % average)
sleep(0.5)

生成的程序运行起来非常慢。