eypsilon/mycrobench

MycroBench | 轻量级PHP时间测量工具

v1.0.4 2023-03-08 21:02 UTC

This package is auto-updated.

Last update: 2024-09-10 14:46:52 UTC


README

此包使用 $_SERVER['REQUEST_TIME_FLOAT']microtime() 来计算实例化时两者之间经过的时间差。它还提供了一个基本的 hrtime() 实现,允许以更高的精度测量处理时间。

查看 ./public/index.php 中的示例,或检查 Vercel 上的实时演示。

composer require eypsilon/MycroBench
use Many\MycroBench;

/**
 * @return array basic usage
 */
MycroBench::get()

// Array
// (
//     [start] => 2022-10-10 16:07:00.172129
//     [ended] => 2022-10-10 16:07:00.302257
//     [took] => 00.130128
//     [mem_usage] => 376.21 KB
//     [mem_peak] => 16.37 MB
//     [included_files_total] => 37
// )

连续请求

使用内部固定的 start 时间获取连续请求之间经过的处理时间。

第一个请求将使用 $_SERVER['REQUEST_TIME_FLOAT'] 作为 start 时间,后续请求将使用前一个请求的 ended 时间。

手动将基准测试的初始开始时间设置为 now。这是可选的,但如果未实例化,则第一次高分辨率时间将错误。

/** Sets the start time for @method getBench() and @method hrBench() to now */
MycroBench::initBench()
/** @param bool true returns additional high resolution times */
MycroBench::getBench(true)

// [start] => 2022-10-10 16:07:00.176997
// [ended] => 2022-10-10 16:07:00.217398
// [took] => 00.040401
// [h_res] => 0.040415356

MycroBench::getBench(true)

// [start] => 2022-10-10 16:07:00.217398
// [ended] => 2022-10-10 16:07:00.239846
// [took] => 00.022448
// [h_res] => 0.022439554

MycroBench::getBench(true)

// [start] => 2022-10-10 16:07:00.239846
// [ended] => 2022-10-10 16:07:00.265409
// [took] => 00.025563
// [h_res] => 0.025560282

高分辨率时间

使用 hrtime() 通过系统的高分辨率时间获取 microtimes

微秒: 00.019045

高分辨率: 0.019044332

// start bench
MycroBench::hrStart()

// do stuff here

// end bench, set first param true to get the result in return
MycroBench::hrEnd(false)

/** @return float|null '0.019044332' */
MycroBench::hrGet()

使用内部固定的开始时间获取高分辨率时间。

/** @return float|null '0.019044332' */
MycroBench::hrBench()

其他

/**
 * microtimestamp to datetime
 *
 * @return string '2022-09-01 17:14:48.5000'
 */
(new MycroBench)->getDate('1662045288.5000') # 'U.u', 'Y-m-d H:i:s.u'

/**
 * datetime to microtimestamp
 *
 * @return string '1662045288.5000'
 */
(new MycroBench)->getDateToMicro('2022-09-01 17:14:48.5000') #'Y-m-d H:i:s.u', 'U.u'

/**
 * Get microtimestamp for the last request. Only filled
 * when @method getBench() has been called
 *
 * @return string|null '1662623500.7135'
 */
MycroBench::getLastDate()

/**
 * Readable bytes
 *
 * @return string '379.67 KB'
 */
MycroBench::readableBytes(memory_get_usage())

/**
 * Default getter
 *
 * start: $_SERVER['REQUEST_TIME_FLOAT']
 * ended: microtime(true)
 *
 * @static alias MycroBench::get()
 *
 * @param bool   enable (array) get_included_files()
 * @param string set a needle to shorten the paths returned in get_included_files()
 * @return array
 */
(new MycroBench)->getAll(true, '/remove/from/included_files/paths')

/**
 * Consecutive getter
 *
 * @static alias MycroBench::getBench()
 *
 * @param bool get additionally higher resolution times
 * @return array
 */
(new MycroBench)->getBenchDiff(true)