【问题标题】:Script B slows down script A脚本 B 减慢了脚本 A
【发布时间】:2018-07-15 03:47:08
【问题描述】:

我在 Raspberry Pi 上使用 Python 2.7。

我运行一个脚本 A,它是一个 for 循环,每 30 秒拍照一次。通常,对于每次迭代,捕获场景并保存大约需要 5 秒,然后它会休眠(大约 25 秒)直到下一次迭代。

一段时间后,我运行了一个脚本 B,它根据脚本 A 拍摄的图像计算东西。所以这两个脚本同时运行。我没有使用子进程或任何东西,只是分别执行两个脚本。

我的问题是:当脚本 B 运行时,脚本 A 会变慢很多,所以有时前 5 秒会变成 25-30 秒,然后一次迭代可以持续 40 秒或更长时间!

您知道为什么脚本 A 不遵守持续时间,以及如何解决这个问题吗?

谢谢:)!

【问题讨论】:

    标签: python time process raspberry-pi


    【解决方案1】:

    我相信如果你在 Linux 环境中,你可以使用 nice 命令来平衡 cpu 的使用。例如:

    nice --12 script.py 
    

    上面的数字代表对cpu好坏的程度,在-20到+19之间。

    【讨论】:

      【解决方案2】:
      1. 如果“脚本 B”的计算量几乎总是相同,您可以从睡眠计时器中减去该时间(以秒为单位)。

      2.您还可以在脚本的几秒钟内获取运行时,您将在脚本执行结束时输出。问题是python程序在继续之前会等待一个完成的脚本。

      import subprocess
      import time
      counter = 0
      script_a_runtime = 0
      script_b_runtime = 0
      
      while True:
          counter += 1
          script_a = 0
          script_b = 0
          script_a_runtime = int(subprocess.check_output(['scripta']))
          if counter >=5:
              counter = 0
              script_b_runtime = int(subprocess.check_output(['scriptb']))
          sleeptime = 30 - script_a_runtime - script_b_runtime
          if sleeptime:
              time.sleep(sleeptime)
      

      3.定时器

      import datetime
      import time
      import subprocess
      script_a_runtime = 0
      script_b_runtime = 0
      
      while True:
          counter += 1
          start_a = datetime.datetime.now()
          subprocess.check_output(['script_a'])
          finish_a = datetime.datetime.now()
          script_a_runtime = finish_a - start_a
          if counter >= 5:
              counter = 0
              start_b = datetime.datetime.now()
              subprocess.check_output(['script_b'])
              finish_b = datetime.datetime.now()
              script_b_runtime = finish_b - start_b
              sleeptime = 30 - script_a_runtime.seconds - script_b_runtime.seconds
          if sleeptime:
              time.sleep(sleeptime)
      

      我认为并排运行那些相互依赖的脚本并不是一个好主意。此外,如果 scriptA/B 在再次运行之前未完成,则可能会出现问题。

      【讨论】:

        猜你喜欢
        • 2017-06-16
        • 1970-01-01
        • 2016-07-30
        • 1970-01-01
        • 2023-01-16
        • 2016-09-30
        • 2021-10-09
        • 1970-01-01
        • 2020-06-19
        相关资源
        最近更新 更多