LoginSignup
39
33

More than 5 years have passed since last update.

PHP: 時間がかかる処理を特定するのを手助けするTimerクラス

Last updated at Posted at 2019-03-19

PHPプログラムで時間がかかる処理を特定するために、処理時間を計測するクラスです。xhprofなどのプロファイリングツールを入れるまでもなさそうなところで使われるのを想定しています。

使い方

下記のコードをプロジェクトの適当なところに置きます。

class Timer
{
    /**
     * @var string|null
     */
    private static $outputFile = 'php://stdout';

    /**
     * @var float
     */
    private $startedOn;

    /**
     * @var string
     */
    private $name;

    public function __construct(?string $name = null)
    {
        $this->name = $name ?? self::getCallerPosition();
        $this->startedOn = \microtime(true);
    }

    public static function setOutputFile(string $filename): void
    {
        self::$outputFile = $filename;
    }

    public function stop(): void
    {
        $duration = \microtime(true) - $this->startedOn;
        $data = \implode(',', [$this->name, $duration]) . "\n";
        \file_put_contents(self::$outputFile, $data, \FILE_APPEND);
    }

    private static function getCallerPosition(): string
    {
        $stack = \debug_backtrace(0, 3);
        if ($stack[2]) {
            $class = $stack[2]['class'] ?? '';
            $class = $class ? $class . '::' : '';
            $function = $stack[2]['function'] ?? '';
            $line = $stack[2]['line'];
            $file = $stack[2]['file'];
            return "{$class}{$function} {$file}:{$line}";
        }

        return 'unknown';
    }
}

測定したい箇所の開始地点でTimernewして、測定を終了する箇所で$timer->stop()します。

class Main
{
    public function doSomething(): void
    {
        Timer::setOutputFile('/tmp/test.log');
        $timer = new Timer();
        \sleep(1); // 時間がかかりそうな処理
        $timer->stop();
    }
}

この状態でプログラムを実行すると、次のようなデータがあつまります:

/tmp/test.log
Main::doSomething /Volumes/dev/php-playground/Timer/Timer.php:75,1.0058917999268

検索用キーワード: ボトルネック 遅い処理 パフォーマンス

39
33
0

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
39
33