1

What is the best way to limit PHP scripts CPU usage from within that script? I am not looking to re-nice the whole PHP system process, but rather keep a PHP script running for longer and adjusting the CPU usage of that script. Basically, it would need to "renice" itself dynamically and specifically to only the script or it would need to slow down the computations / activities it is doing.

Tried proc_nice(), but could not get PHP to increase CPU usage of other scripts after my script finished. The change in my script affected other subsequent scripts/requests. This is, when used in my script, and after increasing the nice level, the nice value stayed for the PHP process in the system.

4
  • You said: "Tried proc_nice(), but could not get it to increase cpu usage", did you really mean "increase"? Commented Jun 25, 2019 at 12:07
  • Maybe it's not an option for you, but personally I'd scale the infra to cope with the demand, or spread the processes out over multiple instances / machines. They're pretty cheap (even free sometimes depending on the scenario). Just a thought based on very limited information. Commented Jun 25, 2019 at 12:14
  • Did you use a positive or negative increment? Also why would this affect other scripts? Commented Jun 26, 2019 at 3:59
  • I was able to change the nice level downwards, but it worked for the whole PHP process. This was OK when my script was running, but could not reset it to default after the script ended. I will clarify this in the question. Commented Jun 27, 2019 at 14:09

1 Answer 1

1

You could usleep() at regular intervals in your code. This will delay script execution for a given number of microseconds leaving more time for other processes.

Sign up to request clarification or add additional context in comments.

1 Comment

I will try this and also will check if my script can check overall CPU use to adjust the 'usleep()' duration accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.