Programming

PHP로 작성된 코드 속도를 어떻게 측정 할 수 있습니까?

procodes 2020. 7. 28. 21:56
반응형

PHP로 작성된 코드 속도를 어떻게 측정 할 수 있습니까?


여러 클래스 (모두 동일한 작업을 수행하는 클래스)가 더 빠르게 실행되는 방법을 어떻게 알 수 있습니까? 그것을 측정하는 소프트웨어가 있습니까?


당신은 (적어도) 두 가지 솔루션을 :

아주 "순진한"것은 코드 실행 전후에 microtime (true)을 사용하여 실행하는 동안 얼마나 많은 시간이 지 났는지를 얻는 것입니다. 다른 답변은 그 말을하고 이미 예를 들었으므로 더 이상 말하지 않을 것입니다.

이 방법은 몇 가지 지침을 벤치마킹하려는 경우 좋은 솔루션입니다. 예를 들어, 두 가지 유형의 함수를 비교하는 것과 같이- "동요 요소"의 평균을 유지하는 것이 수천 번 수행하는 것이 좋습니다.

배열을 직렬화하는 데 걸리는 시간을 알고 싶다면 다음과 같이하십시오.

$before = microtime(true);

for ($i=0 ; $i<100000 ; $i++) {
    serialize($list);
}

$after = microtime(true);
echo ($after-$before)/$i . " sec/serialize\n";

완벽하지는 않지만 유용하며 설정하는 데 많은 시간이 걸리지 않습니다.



전체 스크립트에서 많은 시간이 걸리는 함수를 식별하려는 경우 꽤 잘 작동하는 다른 솔루션은 다음을 사용하는 것입니다.

  • 스크립트에 대한 프로파일 링 데이터를 생성하기 위한 Xdebug 확장
  • 프로파일 링 데이터를 읽고 읽을 수있는 것을 제공하는 소프트웨어. 나는 그중 세 가지를 알고 있습니다.
    • Webgrind ; 웹 인터페이스; 모든 Apache + PHP 서버에서 작동합니다
    • WinCacheGrind ; 창문에서만
    • KCacheGrind ; 아마 리눅스와 리눅스 같은 것; 그게 내가 좋아하는 것, btw

프로파일 링 파일을 얻으려면 Xdebug를 설치하고 구성해야합니다. 문서의 PHP 스크립트 프로파일 링 페이지를 살펴보십시오 .

내가 일반적으로하는 일은 기본적으로 프로파일 러를 활성화하지 않고 (큰 파일을 생성하고 속도를 늦추는 것)XDEBUG_PROFILE GET 데이터 라는 매개 변수를 보내서 필요한 페이지에 대해서만 프로파일 링을 활성화 하는 가능성을 사용하는 것 입니다.
내 php.ini의 프로파일 링 관련 부분은 다음과 같습니다.

xdebug.profiler_enable = 0              ; Profiling not activated by default
xdebug.profiler_enable_trigger = 1      ; Profiling activated when requested by the GET parameter
xdebug.profiler_output_dir = /tmp/ouput_directory
xdebug.profiler_output_name = files_names

(자세한 내용은 설명서를 읽으십시오)

이 스크린 샷은 KcacheGrind의 C ++ 프로그램에서 가져온 것입니다 : (source : sourceforge.net ) PHP 스크립트와 똑같은 것을 얻을 수 있습니다 ;-) (KCacheGrind를 사용하면 WinCacheGrind는 KCacheGrind만큼 좋지 않습니다 ... )http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif



이를 통해 응용 프로그램에서 시간이 걸리는 것을 잘 볼 수 있으며 때로는 모든 것을 느리게 하는 기능 을 찾는 데 도움이 됩니다 ^^

Xdebug는 PHP가 소비 한 CPU 시간을 계산합니다. PHP가 데이터베이스의 응답을 기다리는 경우 (예를 들어) 작동하지 않습니다. 기다리고 있습니다. 따라서 Xdebug는 DB 요청에 많은 시간이 걸리지 않을 것이라고 생각합니다!
이것은 PHP가 아닌 SQL 서버에서 프로파일 링되어야합니다.


이것이 도움이 되길
바랍니다 :-) 재미있게 보내세요!


빠른 작업을 위해 나는 이것을 PHP로한다 :

$startTime = microtime(true);
doTask(); // whatever you want to time
echo "Time:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

http://xdebug.org/ 와 같은 프로파일 러를 사용할 수도 있습니다 .


귀하의 질문에 대한 직접적인 답변은 다음과 같습니다

그것을 측정하는 소프트웨어가 있습니까?

그렇습니다. 왜 아무도 아직 언급하지 않았는지 궁금합니다. 위에서 제안한 답변은 빠른 확인에는 적합하지만 장기적으로나 더 큰 프로젝트에는 확장 할 수 없습니다.

정확하게 구현 된 APM (Application Performance Monitoring) 도구를 사용해보십시오. NewRelic, AppDynamics, Ruxit (모두 무료 버전이 있음)을 확인하여 실행 시간, 리소스 사용량, 모든 애플리케이션의 처리량을 메소드 레벨까지 모니터링하십시오.


간단한 타이밍 클래스를 만들었습니다. 어쩌면 누군가에게 유용 할 수 있습니다.

class TimingHelper {

    private $start;

    public function __construct() {
        $this->start = microtime(true);
    }

    public function start() {
        $this->start = microtime(true);
    }

    public function segs() {
        return microtime(true) - $this->start;
    }

    public function time() {
        $segs = $this->segs();
        $days = floor($segs / 86400);
        $segs -= $days * 86400;
        $hours = floor($segs / 3600);
        $segs -= $hours * 3600;
        $mins = floor($segs / 60);
        $segs -= $mins * 60;
        $microsegs = ($segs - floor($segs)) * 1000;
        $segs = floor($segs);

        return 
            (empty($days) ? "" : $days . "d ") . 
            (empty($hours) ? "" : $hours . "h ") . 
            (empty($mins) ? "" : $mins . "m ") . 
            $segs . "s " .
            $microsegs . "ms";
    }

}

사용하다:

$th = new TimingHelper();
<..code being mesured..>
echo $th->time();
$th->start(); // if it's the case
<..code being mesured..>
echo $th->time();

// result: 4d 17h 34m 57s 0.00095367431640625ms 

프레임 워크의 성능을 빠르게 테스트하려면 index.php 파일을 넣을 수 있습니다

//at beginning
$milliseconds = round(microtime(true) * 1000);

//and at the end
echo round(microtime(true) * 1000) - $milliseconds;

당신은 밀리 초 단위로 실행 시간을 얻을 때마다 . 마이크로 초는 프레임 워크 사례를 테스트하는 데 너무 유용하지 않기 때문입니다.


I've been using XHProf lately http://pecl.php.net/package/xhprof. It was originally developed by Facebook and it comes with a decent web interface.


I'd like to share with you a self made function I use to measure the speed of any existing function up to 10 arguments:

function fdump($f_name='', $f_args=array()){

    $f_dump=array();
    $f_result='';

    $f_success=false;

    $f_start=microtime();
    $f_start=explode(' ', $f_start);
    $f_start=$f_start[1] + $f_start[0];

    if(function_exists($f_name)){

        if(isset($f_args[0])&&is_array($f_args[0])){
            if($f_result=$f_name($f_args)){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[1])){
            if($f_result=$f_name($f_args[0])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[2])){
            if($f_result=$f_name($f_args[0],$f_args[1])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[3])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[4])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[5])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[6])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[7])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[8])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[9])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7],$f_args[8])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[10])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7],$f_args[8],$f_args[9])){
                $f_success=true;
            }
        }
    }
    $f_end=microtime();
    $f_end=explode(' ', $f_end);
    $f_end=$f_end[1] + $f_end[0];

    $f_time=round(($f_end - $f_start), 4);
    $f_dump['f_success']=$f_success;
    $f_dump['f_time']=$f_time;
    $f_dump['f_result']=$f_result;

    var_dump($f_dump);exit;

    //return $f_result;

}

Example

function do_stuff($arg1='', $arg2=''){
    return $arg1.' '.$arg2;
}

fdump('do_stuff',array('hello', 'world'));

Returns

  array(3) {
    ["f_success"]=>
    bool(true)
    ["f_time"]=>
    float(0)            //too fast...
    ["f_result"]=>
    string(11) "hello world"
  }

If it's something that can be tested outside the Web context, I just use the Unix time command.


Zend Studio has built in support for profiling using XDebug or ZendDebugger. It will profile your code, telling you exactly how long every function took. It's a fantastic tool for figuring out where your bottlenecks are.


작업 전후에 타임 스탬프 또는 microtime () 저장과 같은 기본 항목을 사용하여 필요한 시간을 계산할 수 있습니다. 쉬운 일이지만 정확하지는 않습니다. 어쩌면 더 나은 해결책은 Xdebug 일 것입니다.이 작업을 한 적이 없지만 가장 잘 알려진 PHP 디버거 / 프로파일 러 인 것 같습니다.

참고 URL : https://stackoverflow.com/questions/1200214/how-can-i-measure-the-speed-of-code-written-in-php

반응형