cspray/precision-stopwatch

一个用于跟踪精确时间点之间持续时间的小型库。

0.2.0 2023-05-13 18:36 UTC

This package is auto-updated.

Last update: 2024-09-13 21:31:45 UTC


README

通过利用 hrtime 函数,精确到纳秒地计时 PHP 脚本和代码。

安装

Composer 是安装此库的唯一支持方法 Composer

composer require cspray/precision-stopwatch

使用指南

使用提供的功能涉及以下步骤

  1. 创建一个新的 Cspray\PrecisionStopwatch\Stopwatch 实例
  2. 调用 Stopwatch::start()
  3. 做你要计时的事情!
  4. 调用 Stopwatch::mark()(可选,见 标记时间
  5. 调用 Stopwatch::stop()
  6. 使用 Cspray\PrecisionStopwatch\Metrics 获取计时器运行时间的详细信息

下面的代码示例可以通过克隆此存储库并运行 ./examples 中的脚本来执行。

基本用法

<?php declare(strict_types=1);

use Cspray\PrecisionStopwatch\Stopwatch;

require_once __DIR__ . '/vendor/autoload.php';

$stopwatch = new Stopwatch();

$stopwatch->start();

sleep(3);

$metrics = $stopwatch->stop();

echo 'Duration (ns): ', $metrics->getTotalDuration()->timeTakenInNanoseconds(), PHP_EOL;
echo 'Duration (ms): ', $metrics->getTotalDuration()->timeTakenInMilliseconds(), PHP_EOL;

如果你执行此示例,你应该会看到类似以下输出

% > php ./examples/usage-without-marks.php
Total time taken (ns): 1000584755
Total time taken (ms): 1000.584755

标记时间

标记时间允许你检索计时器运行到某个点的时间长度,同时允许计时器继续运行。调用 Stopwatch::mark() 将返回一个 Cspray\PrecisionStopwatch\Marker 实例。除了从 Marker 实例检索到某个点的时间长度外,你还可以使用从 Stopwatch::stop() 返回的 Metrics 检索标记之间的时间长度。

<?php declare(strict_types=1);

use Cspray\PrecisionStopwatch\Stopwatch;

require_once dirname(__DIR__) . '/vendor/autoload.php';

// .75 seconds
$sleepTime = 750_000;

$stopwatch = new Stopwatch();

$stopwatch->start();

usleep($sleepTime);

$mark1 = $stopwatch->mark();

usleep($sleepTime);

$mark2 = $stopwatch->mark();

usleep($sleepTime);

$mark3 = $stopwatch->mark();

usleep($sleepTime);

$metrics = $stopwatch->stop();

echo 'Total time taken (ns): ', $metrics->getTotalDuration()->timeTakenInNanoseconds(), PHP_EOL;
echo 'Total time taken (ms): ', $metrics->getTotalDuration()->timeTakenInMilliseconds(), PHP_EOL;

echo PHP_EOL;

$between1And3 = $metrics->getDurationBetweenMarkers($mark1, $mark3);
echo 'Time take between 1st and 3rd mark (ns): ', $between1And3->timeTakenInNanoseconds(), PHP_EOL;
echo 'Time take between 1st and 3rd mark (ms): ', $between1And3->timeTakenInMilliseconds(), PHP_EOL;

echo PHP_EOL;

echo 'Time taken up to 3rd mark (ns): ', $mark3->getDuration()->timeTakenInNanoseconds(), PHP_EOL;
echo 'Time taken up to 3rd mark (ms): ' , $mark3->getDuration()->timeTakenInMilliseconds(), PHP_EOL;

如果你执行此示例,你应该会看到类似以下输出

% > php ./examples/usage-without-marks.php
Total time taken (ns): 3000608258
Total time taken (ms): 3000.608258

Time take between 1st and 3rd mark (ns): 1500407710
Time take between 1st and 3rd mark (ms): 1500.40771

Time taken up to 3rd mark (ns): 2250497069
Time taken up to 3rd mark (ms): 2250.497069