python function(or a code block) runs much slower with a time interval in a loop

你。 提交于 2019-12-03 21:30:46

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

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)

the result is:

0.031275457000447204 15.031275457000447
1.0220358229998965 16.022035822999896
0.41462676399987686

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...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!