7

I have some scripts that use a ton of cpu is it possible to cap the amount of cpu a process is allowed to use? I am running on CentOs 5.5 by the way.

1
  • Do you mean in the php code itself? You may be able to limit the php scripting engine through the OS but that wouldn't be programming related Commented Sep 26, 2010 at 3:04

3 Answers 3

12

I helped a fellow PHP coder create PHP scripts which address a similar issue. These are long-running PHP scripts which generate a lot of load. Since they're long running, the goal was to "pause" them if load gets too high. The script has a function similar to:

function get_server_load()
{
    $fh = fopen('/proc/loadavg', 'r')
    $data = fread($fh, 6);
    fclose($fh);
    $load_avg = explode(" ", $data);
    return floatval(trim($load_avg[0]));
}

The script calls get_server_load() during each loop, and if the load is greater than a given max, it sleeps for 30 seconds and checks again:

set_time_limit(120);
while(get_server_load() > $max_load)
    sleep($load_sleep_time);

This allows the script to give CPU time back to the server during periods of high load.

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

1 Comment

This is nice approach, but note that you are returning int, not float, so you can't get load average of 0.9 eg.
10

maybe you could use nice?

Comments

-3

PHP is considered a scripting language, and does not have such low level access to the hardware.

Instead, what you can do is use functions like "set_time_limit()"

http://php.net/manual/en/function.set-time-limit.php

and memory_limit in your php.ini

http://php.net/manual/en/ini.core.php

Those are the recommended methods, but the closest you'll get to what you want are probably a combination of "sleep()"

http://php.net/manual/en/function.sleep.php

and getting the current CPU load with "exec('uptime');". Note that you may or may not have access to those system commands.

2 Comments

The load average is available in /proc/loadavg under linux. It doesn't require low level access to the hardware, it's a function of the operating system.
With this approach you will only abort a script, not pause or limit it's cpu consumption.

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.