为避免在电子纸屏幕上显示静态内容时的繁忙或效率低下的等待而采取适当的策略?

问题描述

我的应用程序使用各种“插件”对象更新了电子纸屏幕。每个对象代表一个模块,并带有自己的工作人员来创建图像。图像会显示一段时间,然后切换到队列中的下一个图像。每个对象都有自己的计时器,该计时器取决于其关联工作程序产生的数据。该计时器可以响应各种外部输入(例如,用户开始播放音乐,出现天气警报)而更改。

将工作人员排队等待并进行一次更新,然后在需要时对屏幕进行更新。

我目前在更新/显示循环的末尾使用sleep(1)来避免在什么都没有发生时忙于等待。是否有更好的策略来改善由此消耗的资源?在实验上,我发现通过增加sleep()值,此过程的cpu负载下降了一点(如top所监视)。

问题:是否存在一种更节省资源的方式来设置显示循环(请参见下文)?

我已经阅读了threading and using join,但是在这里看来不合适,因为等待时间是已知的,并且代码没有在等待某些外部资源可用。它只是在等待计时器到期。

以下是显示循环的示例:

# list objects 
plugins = [updater_obj1,updater_obj2,updater_obj3]


plugin_cycle = itertools.cycle(plugins)
this_plugin = next(plugin_cycle)

while True:
   
   # update each object to ensure there is fresh data to display on demand
   for i in plugins:
      i.update()

   # only update the display when the object's timer has run down
   if this_plugin.timer_expired():
      this_plugin = next(plugin_cycle) # move to the next item in the list
      this_plugin.set_timer() # reset the timer
      epd.write(plugin.image) # update the E-paper display with a new image
   
   sleep(1)

解决方法

添加类似timer_expires()的方法,该方法为每个插件返回计时器到期的时间戳,然后它可以休眠直到它到期,因此不必继续检查

while True:
   
   # update each object to ensure there is fresh data to display on demand
   for i in plugins:
      i.update()
   
   # sleep for the right amount of time
   sleep(this_plugin.timer_expires() - time())
   
   # update the display
   this_plugin = next(plugin_cycle) # move to the next item in the list
   this_plugin.set_timer() # reset the timer
   epd.write(plugin.image) # update the E-paper display with a new image