Can I throttle the max CPU usage of a php script?

后端 未结 3 2185
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-15 23:54

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.

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-16 00:38

    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.

提交回复
热议问题