【发布时间】:2012-10-30 19:13:47
【问题描述】:
下面的代码非常通用。在它的最终状态下,它将运行一些操作(例如从串行流中采样数据),但我现在的目标是优化循环结构以尽可能快地运行。
目前,在 if 语句跳闸之前,我的最大频率约为 100-140。
有没有更有效的方法来运行它?
注意:我知道 while 循环本质上是空的。当然,它运行速度的限制因素将是我在其中调用的函数。我要确保的是 while 循环中的代码尽可能高效地运行
import time
frequency = float(raw_input("enter sampling frequency in Hz: "))
zero_time=time.time()
i=0
try:
while True:
sample_start_time=time.time()
print 'sample',i, 'taken at', sample_start_time-zero_time
i+=1
sample_end_time=time.time()
if 1/frequency-(sample_end_time-sample_start_time)<0:
print "sampling frequency is too large...closing"
break
time.sleep(1/frequency-(sample_end_time-sample_start_time))
except KeyboardInterrupt:
pass
【问题讨论】:
-
专业提示:使用
timeit.default_timer()而不是time.time()在任何平台上获得最佳计时器分辨率。 -
你为什么要定时打印语句?
-
print阻塞 tty,所以你真的不想计时。 -
似乎很难“优化”一个原本有效的空,而.. [可能] 如果使用局部变量绑定进行计算,可以节省微不足道的时间 可能(看起来反正更好)。 Python 不是为 RT 操作而设计的,它通常也不在 RT 操作系统上运行.. 这也会影响
time.sleep(例如,参见stackoverflow.com/questions/7273474/…).. 请记住。 -
只有我一个人,还是他真的问如何优化“while: do_nothing”循环的while?
标签: python time python-2.7 while-loop