这里做一些php性能的测试,获取循环生成数据的代码执行时间和消耗的内存,并用到了一些内置函数
环境:PHP7.2 + Apache2.4 ,这里在php.ini中设置最大允许内存:memory_limit = 2048M,重启apache
以生成1000万条数据为例
echo '
PHP批量生成数据性能测试
';$start_memory = memory_get_usage();
$arr = array();
$t1 = microtime(true);
for ($i=0; $i <10000000 ; $i++) {
$arr[] = "('h".$i."','熊其明','男','".mt_rand(11111111,99999999)."')".PHP_EOL;
}
$t2 = microtime(true);
@ file_put_contents('allData.txt',implode(',',$arr)) or die("生成数据失败!");
$t3 = microtime(true);
$end_memory = memory_get_usage();
$num = count($arr);
unset($arr);
echo '成功生成数据:'.($num/10000).'万条'.'
';
echo '循环生成'.($num/10000).'万条数据所耗时间:'.round($t2-$t1,3).'s
';
echo '将'.($num/10000).'万条数据插入文件中所耗时间:'.round($t3-$t2,3).'s
';
echo '整个过程耗内存:'.round(($end_memory-$start_memory)/(1024*1024),3).'M
';
echo '回归正常时内存为:'.round(memory_get_usage()/(1024*1024),3).'M
';
microtime() 返回时间,单位是s,加上 true 参数, 返回的将是一个浮点类型
使用 round() 取出小数点后 3 位
memory_get_usage() 返回此时的所使用的内存,单位是B
结果是:
PHP批量生成数据性能测试
成功生成数据:1000万条
循环生成1000万条数据所耗时间:8.047s
将1000万条数据插入文件中所耗时间:1.407s
整个过程耗内存:1276.925M
回归正常时内存为:0.381M
转载:非常欢迎各位朋友分享到个人站长或者朋友圈,但转载请说明文章出处“来源熊其明个人博客”或者文章真实出处。
很赞哦! (1)