您的位置:首页 > 编程语言 > PHP开发

PHP性能测试Part 1 - Counting Loops(计数循环) - count()

2012-07-19 23:04 302 查看
导读:

以下几篇文字,参考国外网站http://www.phpbench.com/ ,感谢Chris
Vincent 的工作。我所做的,就是重新实践,不过,也加入一些自己的思考,并明确测试环境。并且,会将更新后的脚本放置在SAE,具体地址后面会附上。

本地测试环境:

php 5.4.3

mysql 5.5.24

Apache 2.2.22

CPU T6670

Memory 2GB

OS Win7 32bit

说明

1 脚本采用浏览器短输出而非cli方式,所以,使用了<br />;

2 SAE PHP版本并非5.4,所以,不支持新特性$_SERVER['REQUEST_TIME_FLOAT']。

线上DEMO

依赖SAE。

详细

PART 1 Counting Loops(计数循环)

原测试脚本

A

<?php

// Initial Configuration
global $x;
$i   = 0;
$tmp = '';
while($i < 10000) {
$tmp .= 'a';
++$i;
}
$x = array_fill(5, 1000, $tmp);
unset($i, $tmp);

// Test Source
function Test3_1() {
global $x;

/* The Test */
$t = microtime(true);
$size = count($x);
for ($i=0; $i<$size; $i++);

return (microtime(true) - $t);
}

// Variable Clean-up
function Test3_End() {
global $x;
unset($x);
}

B

<?php

// Initial Configuration
global $x;
$i   = 0;
$tmp = '';
while($i < 10000) {
$tmp .= 'a';
++$i;
}
$x = array_fill(5, 1000, $tmp);
unset($i, $tmp);

// Test Source
function Test3_2() {
global $x;

/* The Test */
$t = microtime(true);
for ($i=0; $i<count($x); $i++);

return (microtime(true) - $t);
}

// Variable Clean-up
function Test3_End() {
global $x;
unset($x);
}


更新后脚本

<?php
echo '做for循环,步进上限为数组长度 10000 时,<br />提前 count() 及没有提前 count() 的区别:<br /><br />';
$x = array_fill(0, 10000, 'a');	// 填充数组,数组长度为 10000, 值大小为 9.5367431640625MB

// 提前计算好大小
function with_pre_calc() {

global $x;
$lst = microtime(true);			// 循环开始时间 loop start time 浮点型
$size = count($x);
for ($i=0; $i<$size; $i++);
return microtime(true) - $lst;
}

// 没有提前计算好大小
function without_pre_calc() {

global $x;
$lst = microtime(true);			// 循环开始时间 loop start time 浮点型
for ($i = 0; $i < count($x); $i++);
return microtime(true) - $lst;
}

echo '提前计算好大小: ' . with_pre_calc() . ' 秒'
. '<br />'
. '没有提前计算好: ' . without_pre_calc() . ' 秒'
. '<br />';

unset($x);
echo '脚本总计耗时为: ' . (microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) . ' 秒';


测试结果

本地

做for循环,步进上限为数组长度 10000 时,

提前 count() 及没有提前 count() 的区别:

提前计算好大小: 0.0055069923400879 秒

没有提前计算好: 11.517592191696 秒

脚本总计耗时为: 11.528949975967 秒

SAE(点击访问

做for循环,步进上限为数组长度 10000 时,

提前 count() 及没有提前 count() 的区别:

提前计算好大小: 0.00195813179016 秒

没有提前计算好: 8.76361608505 秒

结论

使用提前计算for循环步进上限,使之成为常量,而非计算式。( 服务器就是比笔记本好啊)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: