PerformanceUtils.php 1.49 KB
<?php

namespace common\helpers;

use function explode;
use function microtime;
use function sprintf;
use function floatval;
use function memory_get_usage;
use function round;
use function floor;
use function date;

/**
 * 性能测试工具
 */
class PerformanceUtils
{
    const MEM_UNIT_KB = 1;
    const MEM_UNIT_MB = 2;

    /**
     * 返回毫秒级时间戳
     * @return float
     */
    public static function getMsTime()
    {
        list($t1, $t2) = explode(' ', microtime());
        return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }

    /**
     * 获取当前系统消耗的内存
     * @param int $unit
     * @return float|int
     */
    public static function getMemoryUsage($unit = self::MEM_UNIT_MB)
    {
        $memoryUsage = memory_get_usage();
        if ($unit == self::MEM_UNIT_KB) {
            return round($memoryUsage / 1000, 3);
        } elseif ($unit == self::MEM_UNIT_MB) {
            return round($memoryUsage / (1024 * 1024), 3);
        } else { // 默认字节
            return $memoryUsage;
        }
    }

    /**
     * 返回带毫秒的日期
     * @return string
     */
    public static function getMsDateTime()
    {
        $mTimestamp = sprintf("%.3f", microtime(true)); // 带毫秒的时间戳
        $timestamp = floor($mTimestamp); // 时间戳
        $milliseconds = round(($mTimestamp - $timestamp) * 1000); // 毫秒
        $msDatetime = date("Y-m-d H:i:s", $timestamp) . '.' . $milliseconds;

        return $msDatetime;
    }
}