LoginSignup
32
33

More than 5 years have passed since last update.

phpでコード中のボトルネックをさくっと見つける

Posted at

コード中、処理時間がかかってる箇所を探す関数です。
コード中にちりばめれば、どの行間で時間かかってるか確認できます。

def.php

function debug_time(){

    $debug = current(debug_backtrace());

    static $start_time = 0;
    static $pre_debug = null;
    static $pre_time = 0;

    $time = microtime(true);
    if(!$start_time) $start_time = $time;

    if($pre_time){
        echo sprintf('<div>[%s(%d) - %s(%d)]: %d ms(ttl:%d ms)</div>', 
            basename($pre_debug['file']), $pre_debug['line'],
            basename($debug['file']), $debug['line'],
            ($time * 1000 - $pre_time * 1000),
            ($time * 1000 - $start_time * 1000)
        );
    }

    $pre_debug = $debug;
    $pre_time = $time;
}

hoge.php

debug_time();//何も考えずコード全体にコピペしまくる

//なんらかの処理
for($i = 0; $i < 100; $i++) some_function1();

debug_time();

//なんらかの処理
for($i = 0; $i < 100; $i++) some_function2();

debug_time();

//なんらかの処理
for($i = 0; $i < 100; $i++) some_function3();

debug_time();


result

[hoge.php(1) - hoge.php(5)]: 200 ms(ttl:200 ms) //hoge.phpの1行目から5行目に200msかかった。累計200ms
[hoge.php(5) - hoge.php(10)]: 800 ms(ttl:1000 ms) //hoge.phpの5行目から10行目に800msかかった。累計1000ms
[hoge.php(10) - hoge.php(15)]: 100 ms(ttl:1100 ms)//hoge.phpの10行目から15行目に100msかかった。累計1100ms

つまり5行目から10行目の処理に改善が必要とわかります。
異なるファイルにまたがってもOKです。

32
33
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
32
33