php–循环展开

在北大体系结构中,听到一项循环展开的技术,带着问题用自己熟悉的语言测试一下,果然如老师所说的一样。

代码如下:

<?PHP
error_reporting(0);
ini_set("display_error",0);
ini_set("memory_limit","999M");

function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}

function test1(){
	$list = array();
	$time_start = microtime_float();
	for($i=1;$i<=100000;$i++){
		$list[$i]=$i;
	}
	$time_end = microtime_float();
	$time = $time_end - $time_start;
	echo "test1 in $time seconds<br/>";
}

function test2(){
	$list = array();
	$time_start = microtime_float();
	for($i=1;$i<=100000;$i++){
		$list[$i]=$list[$i]+$list[$i-1];
	}
	$time_end = microtime_float();
	$time = $time_end - $time_start;
	echo "test2 in $time seconds<br/>";
}

function test3(){
	$list = array();
	$time_start = microtime_float();
	for($i=1;$i<=100000;$i++){
		$list[$i]=$list[$i]+100000;
	}
	$time_end = microtime_float();
	$time = $time_end - $time_start;
	echo "test3 in $time seconds<br/>";
}
test1();
test2();
test3();




多次运行结果如下:

test1 in 0.015625 seconds
test2 in 0.25 seconds
test3 in 0.140625 seconds


test1 in 0.03125 seconds
test2 in 0.140625 seconds
test3 in 0.140625 seconds


test1 in 0.03125 seconds
test2 in 0.1875 seconds
test3 in 0.140625 seconds


test1 in 0.03125 seconds
test2 in 0.15625 seconds
test3 in 0.140625 seconds

基本可以看出,test1用的时间最短,其次是test3,最长是test2.

这就是知道编译器原理之后,写代码注意的细节问题。详细原理有时间给大家具体讲解。!

If you are going for the movie look
christina aguilera weight loss DIRK PITT novels finally coming to big screen

spandex blend 32 inseam
snooki weight lossTwink Solid G String Underwear Available Now for Free at DealbyEthan
youjizz
此条目发表在 网站开发 分类目录,贴了 标签。将固定链接加入收藏夹。

评论功能已关闭。