且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

python函数(或代码块)以一定的时间间隔在循环中运行慢得多

更新时间:2023-10-27 17:02:10

(不是答案-太长而无法发表评论)

(not an answer - but too long to post as comment)

我做了一些实验,并通过(c4>进行了一些简化).

i did some experimentation and ran (something slightly simpler) through timeit.

from timeit import timeit
import time

n_loop = 15
n_timeit = 10
sleep_sec = 0.1

t = range(100000)

def with_sleep():
    for i in range(n_loop):
        s = sum(t)
        time.sleep(sleep_sec)

def without_sleep():
    for i in range(n_loop):
        s = sum(t)

def sleep_only():
     for i in range(n_loop):
        time.sleep(sleep_sec)

wo = timeit(setup='from __main__ import without_sleep',
           stmt='without_sleep()',
           number = n_timeit)
w = timeit(setup='from __main__ import with_sleep',
            stmt='with_sleep()',
            number = n_timeit)
so = timeit(setup='from __main__ import sleep_only',
            stmt='sleep_only()',
            number = n_timeit)

print(so - n_timeit*n_loop*sleep_sec, so)
print(w - n_timeit*n_loop*sleep_sec, w)
print(wo)

结果是:

0.031275457000447204 15.031275457000447
1.0220358229998965 16.022035822999896
0.41462676399987686

第一行只是检查睡眠功能是否使用了大约n_timeit*n_loop*sleep_sec秒.因此,如果此值为 small -应该没问题.

the first line is just to check that the the sleep function uses about n_timeit*n_loop*sleep_sec seconds. so if this value is small - that should be ok.

但是,正如您所看到的-您的发现仍然存在:具有睡眠功能的循环(减去睡眠所用的时间)比没有睡眠的循环要花更多的时间...

but as you see - your findings remain: the loop with the sleep function (subtracting the time sleep uses) takes up more time than the loop without sleep...

我不认为python可以在不休眠的情况下优化循环(c编译器可能会使用该变量;从不使用变量s).

i don't think that python optimizes the loop without sleep (a c compiler might; the variable s is never used).