[PHP] load average throttle

PHP 2014. 5. 15. 13:50




load avg와 cpu 프로세서 수 간의 비율을 대충 체크하여 throttle 하는 간략한 방법.




// 데몬 형태로 돌아가는 프로세스라 가정

while (true) {

    // 머신사용률이 50% 이하일 경우에만 실행

    if (Throttle::isOK(50) === true) {

        // 조금은 빡센 작업

    }


    sleep(5);

}



// load avg와 cpu 프로세서수를 기반으로 계산된 머신사용률 체크 클래스

class Throttle

{

    // cpu 프로세서 수

    private static $cpu_count = 0;


    // 머신사용률이 지정 threshold 미만이면 true, 아니면 false 반환

    public static function isOK($threshold=100)

    {

        // threshold 초기화. 잘못 지정했다면 100% 로

        $threshold = (float)$threshold;

        if (!$threshold) $threshold = 100;


        // 최근 1분 load avg 가져오기

        $load_avg = self::getLoadAvg();


        // cpu 프로세서 수 가져오기

        $cpu_count = self::getCpuCount();

        if (!$cpu_count) return false;


        // 머신사용률 계산

        $load_avg_percentage = ($load_avg / $cpu_count) * 100;


        // 결과값 반환

        return $threshold > $load_avg_percentage;

    }


    // 최근 1분 load avg 반환

    private static function getLoadAvg()

    {

        // 함수가 있으면 함수 사용

        if (function_exists('sys_getloadavg')) {

            $load_avg = sys_getloadavg();

        }

        // 함수가 없으면 /proc/loadavg 파일을 읽어서 사용

        else {

            $load_avg_path = '/proc/loadavg';

            if (!file_exists($load_avg_path)) return false;


            $content = trim(file_get_contents($load_avg_path));

            if (!$content) return false;


            $load_avg = explode(' ', $content);

        }


        return $load_avg[0];

    }


    // cpu 프로세서 수 반환

    private static function getCpuCount()

    {

        // 최초 1회만 카운트

        if (self::$cpu_count < 1) {

            $cpuinfo_path = '/proc/cpuinfo';

            if (!file_exists($cpuinfo_path)) return false;


            $fp = fopen($cpuinfo_path, 'r');

            if (!$fp) return false;


            while (($line = fgets($fp)) !== false) {

                if (strpos($line, 'processor')===false) continue;


                ++self::$cpu_count;

            }

            fclose($fp);

        }


        return self::$cpu_count;

    }

}








Posted by bloodguy
,