PerformanceUtils.php
1.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<?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;
}
}