php性能测试记录和统计时间(微秒)和内存使用情况/**
* php性能测试记录和统计时间(微秒)和内存使用情况
* 使用方法:
*
* testing('begin'); // 记录开始标记位
* // ... 区间运行代码
* testing('end'); // 记录结束标签位
* echo testing('begin','end',6); // 统计区间运行时间 精确到小数后6位
* echo testing('begin','end','m'); // 统计区间内存使用情况
* 如果end标记位没有定义,则会自动以当前作为标记位
* 其中统计内存使用需要 $MEMORY_LIMIT_ON 为true才有效
*
* @param string $start 开始标签
* @param string $end 结束标签
* @param integer|string $dec 小数位或者m
* @return mixed
*/
function testing($start, $end = '', $dec = 4)
{
$MEMORY_LIMIT_ON = function_exists('memory_get_usage');
static $_info = [];
static $_mem = [];
if (is_float($end)) { // 记录时间
$_info[$start] = $end;
} elseif (!empty($end)) { // 统计时间和内存使用
if (!isset($_info[$end])) $_info[$end] = microtime(TRUE);
if ($MEMORY_LIMIT_ON && $dec == 'm') {
if (!isset($_mem[$end])) $_mem[$end] = memory_get_usage();
return number_format(($_mem[$end] - $_mem[$start]) / 1024);
} else {
return number_format(($_info[$end] - $_info[$start]), $dec);
}
} else { // 记录时间和内存使用
$_info[$start] = microtime(TRUE);
if ($MEMORY_LIMIT_ON) $_mem[$start] = memory_get_usage();
}
return NULL;
}
测试:/**
* 判断某个整数是否是质数(素数)
* @param $n
* @return bool
*/
function isPrime($n)
{
$n = intval($n);
if ($n <= 0) {
return FALSE;
}
if ($n <= 3) {
return $n > 1;
} elseif ($n % 2 === 0 || $n % 3 === 0) {
// 排除能被2整除的数(2x)和被3整除的数(3x)
return FALSE;
} else {
// 排除能被6x+1和6x+5整除的数
for ($i = 5; $i * $i <= $n; $i += 6) {
if ($n % $i === 0 || $n % ($i + 2) === 0) {
return FALSE;
}
}
return TRUE;
}
}
testing('begin');
for ($i = 1, $sum = 0; $i <= 10000; $i++) {
$a[] = $i; // 测试内存
if (isPrime($i)) {
echo $i . " ";
}
}
testing('end');
echo "\n";
echo testing('begin', 'end', 6); // 0.054209
echo "\n";
echo testing('begin', 'end', 'm'); // 516