简体   繁体   English

如何减少python程序的CPU和内存使用率?

[英]How do I reduce CPU and memory usage by a python program?

I have a python program that uses a lot of my CPU's resources. 我有一个使用大量CPU资源的python程序。 While it is fine on my regular PC, I'm afraid it might be too much to handle for my Raspberry Pi. 虽然在我的常规PC上还可以,但恐怕Raspberry Pi可能处理不了。 Speed is not an issue. 速度不是问题。 I don't care if my code is executed slowly as I am implementing a real time system that executes the code only once every few hours, but my CPU needs to be freed up as I would also be running other processes simultaneously. 我不在乎我的代码执行速度是否缓慢,因为我正在实现一个实时系统,该系统每隔几个小时执行一次代码,但是我的CPU需要释放,因为我还将同时运行其他进程。 Is there anyway I can reduce the resources that it takes from the CPU at the cost of speed of execution? 无论如何,我是否可以以执行速度为代价减少从CPU占用的资源? Any help would be appreciated, thank you 任何帮助,将不胜感激,谢谢

While you sure can tinker with your program and make it more optimized, the fact is that all programs are generally designed to take as much CPU as they need in order to finish in smallest time possible. 尽管您可以确定自己的程序,并对其进行优化,但事实是,通常设计所有程序时都需要占用尽可能多的CPU,以便在尽可能短的时间内完成。

I see two ways to achieve your goal: 我看到两种方法可以实现您的目标:

  1. Raspberry pi is Linux right? Raspberry pi是Linux吗? So just lower process priority of the python interpreter running your script. 因此,运行脚本的python解释器的进程优先级较低。 this would make sure that other programs can have CPU if they need it 这样可以确保其他程序在需要时可以拥有CPU

  2. In your script, sleep for few milliseconds every few milliseconds.. ugly, but could do the trick 在您的脚本中,每隔几毫秒睡眠几毫秒..很难看,但是可以解决问题

But option one is probably way to go. 但是选择一可能是可行的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM