It's not the first time I get a too much cpu load warning from my hosting. The code is just some random php script with mysql queries, nothing fancy. (THe tables are nothing extraordinary, a few hundred lines maximum and I always limit them if requested.
I don't mind if it runs for 0.15 second instead of 0.05, so is there a way I can control process priority or limit cpu load?
Thanks!
In the Power Options window, expand Processor power management, and then expand Maximum processor state. Now click on On battery and set the maximum threshold value for CPU utilization.
The easiest way to limit CPU usage of a process on a Windows 11/10 computer is to limit Processor power. Go to Control Panel. Maximum Processor State and lower it to 80% or whatever you want. Using software that measures CPU temperatures like 'Speed fan', you will see that temperatures drop.
If this is a dameon or program that runs for long time add sleep()
/usleep()
. A small sleep will reduce your CPU usage dramatically.
Following code will consume a lot of cpu
while(...){
//do stuff
}
Because you are not giving room for CPU to do other task here. change it to
while(...){
//do stuff
sleep(1);
}
This will greatly decrease your CPU usage. 1 second for CPU is a lot of time to do other task.
To sleep that extra 0.1
second (0.15 - 0.05
) use usleep().
usleep(100000);
In principle, on Unixish system (Linux, BSD, etc.), you could use the proc_nice()
function to change the process priority, like this:
proc_nice( 20 ); // now this process has very low priority
However, there are a couple of major caveats here that make it less useful in practice:
proc_nice()
might be disabled for security reasons even on systems that could technically support it.What you could try to do, if your webhost allows it, is to start a background process for the long-running task, so that your webserver can get back to serving requests while it's running. You can even use the nice
shell command to lower the priority of the background process, like this:
exec( "nice nohup php -f slow_script.php < /dev/null > output.txt 2>&1 &" );
Once the slow script has finished, you can get its output by downloading output.txt
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With