PHP输出当前程序运行过程占用内存

<?php

// 记录开始内存状态
$startMemory = memory_get_usage();
//生成包含1-100000为数据元素的数组
$array = range(1, 980000);
//计算数组占用的内存空间大小(单位为字节)
$bytes = memory_get_usage() - $startMemory;
echo size_format($bytes);

// 字节格式化(转换为最佳单位展示)
function size_format($bytes, $decimals = 2) {
    
    
    $units = array(
        'TB' => 1099511627776, // pow( 1024, 4)
        'GB' => 1073741824, // pow( 1024, 3)
        'MB' => 1048576, // pow( 1024 2)
        'KB' => 1024, // pow( 1024, 1)
        'B ' => 1
    );
    foreach ($units as $unit => $mag) {
    
    
        if ($bytes >= $mag) {
    
    
            return number_format($bytes / $mag, $decimals) . ' ' . $unit;
        }
    }
    return false;
}

猜你喜欢

转载自blog.csdn.net/qq_35606400/article/details/132842853