最天想研究一下pear到底是什么东西,找了资料看了看,发现在windows下安装pear好像不难。装完pear,看了一篇关于pear下benchmark的文章,觉得以后可能用到,作下笔记,以便日后好拿来用。
benchmark是一个测试代码执行时间的工具类。其中包含三个类文件。分别是Timer.php、Iterate.php和Profiler.php
笔记代码如下:
- require 'Benchmark/Timer.php';
- require 'Benchmark/Iterate.php';
- //产生随机数方法:主要利用mt_rand()
- function create_password($pw_length =0)
- {
- $randpwd = '';
- for($i = 0; $i < $pw_length; $i ++) {
- $randpwd .= chr ( mt_rand ( 33, 126 ) );
- }
- return $randpwd;
- }
- //产生随机数方法:主要利用array_rand()
- function make_password( $length = 0 )
- {
- $chars = array('a','b','c','d','e','f','g','h', 'i','j','k','l','m','n','o','p','q','r','s', 't','u','v','w','x','y','z','A','B','C','D', 'E','F','G','H','I','J','K','L','M','N','O', 'P','Q','R','S','T','U','V','W','X','Y','Z', '0','1','2','3','4','5','6','7','8','9','!', '@','$','%','^','&','*','(',')','-','_', '[',']','{','}','<','>','~','`','+','=',',', '.',';',':','/','?','|');
- $keys = array_rand($chars,$length);
- $password ='';
- for($i = 0; $i < $length; $i++)
- {
- $password .= $chars[$keys[$i]];
- }
- return $password;
- }
- //测试两个生成随机密码方法的性能
- //测试1:用Benchmark_Timer测试两个方法的执行时间,timer可以同时测试多行代码之间的执行时间
- $timer = new Benchmark_Timer();
- $timer->start();
- $timer->setMarker("create_password方法:");
- create_password(32);
- $timer->setMarker("make_password方法:");
- make_password(32);
- $timer->stop();
- $timer->display();//用表格的方式输出测试结果
- //测试1 end
- echo "
";- //测试2:用Benchmark_Iterate分别测试两个函数执行的平均时间,iterate可以同时调用同一个函数以取得其平均执行时间
- //分别执行 10次,得平均执行时间
- $iterate = new Benchmark_Iterate();
- $iterate->run(10,'create_password',32);
- var_dump($iterate->get());
- $iterate->run(10,'make_password',32);
- var_dump($iterate->get());
- //测试2 end
- ?>
测试1的结果为:
测试2的结果为:
array(12) {
[1]=>
string(8) "0.000084"
[2]=>
string(8) "0.000066"
[3]=>
string(8) "0.000066"
[4]=>
string(8) "0.000071"
[5]=>
string(8) "0.000061"
[6]=>
string(8) "0.000061"
[7]=>
string(8) "0.000062"
[8]=>
string(8) "0.000062"
[9]=>
string(8) "0.000064"
[10]=>
string(8) "0.000063"
["mean"]=>
string(8) "0.000066"
["iterations"]=>
int(10)
}
array(12) {
[1]=>
string(8) "0.000085"
[2]=>
string(8) "0.000074"
[3]=>
string(8) "0.000070"
[4]=>
string(8) "0.000073"
[5]=>
string(8) "0.000071"
[6]=>
string(8) "0.000069"
[7]=>
string(8) "0.000070"
[8]=>
string(8) "0.000070"
[9]=>
string(8) "0.000072"
[10]=>
string(8) "0.000071"
["mean"]=>
string(8) "0.000072"
["iterations"]=>
int(10)
}
mean为函数的平均执行时间