PHP本身的速度已经相当快了。一般来说,速度的瓶颈是等待数据库查询执行完成于从远程URL中提取内容等。由于Web平台的特点,PHP等web 脚本语言本身可能实现不了它应有的效率。在速度优化过程中增加更多的不定因素和复杂性。下面就介绍如何测试和发现代码中存在的性能问题的技术。Apache为Java向Oracle宣战

项目开始前,思维里应该有最基本的优化习惯并合理利用。项目的后期优化的成本就非常高了,可能你会重构某些代码块。下面讨论一些平时可以避免影响效率的习惯和方法。
功能相同的函数,谁的效率最高。这里有个经验,一般相同功能的函数,新版本的效率更高(注意PHP版本)。
滥用正则表达式(能满足需要的字符串函数代替正则表达式)。
平时对字符串、排序、数组方面研究积累。

需要说明一点,我们需要综合考虑函数在你的程序中被调用的次数、可读性、可维护性,如果只是为了省下微不足道的一小点时间,而增加了额外的复杂性就不值得了。

计算函数执行时间

01 <?php
02 /*
03  * To change this template, choose Tools | Templates
04  * and open the template in the editor.
05  */
06 //定义一个字符串
07 $str="netconcepts.cn";
08  
09 //从这里开始计时
10 $start=microtime(true);
11  
12 //要测试的函数
13 $md5=md5($str);
14 $endtime=microtime(true) - $start;
15 echo 'Md5函数执行时间:'.$endtime;
16 ?>

计算程序执行时间-PEAR Benchmark 模块
timer_example.php

01 <?php
02 /**
03  * timer_example.php
04  *
05  * PHP version 4
06  *
07  * Copyright (c) 2001-2006 Sebastian Bergmann <sb@sebastian-bergmann.de>.
08  *
09  * This source file is subject to the New BSD license, That is bundled
10  * with this package in the file LICENSE, and is available through
11  * the world-wide-web at

13  * If you did not receive a copy of the new BSDlicense and are unable
14  * to obtain it through the world-wide-web, please send a note to
15  * license@php.net so we can mail you a copy immediately.
16  *
17  * @category  Benchmarking
18  * @package   Benchmark
19  * @author    Sebastian Bergmann <sb@sebastian-bergmann.de>
20  * @copyright 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
21  * @license    http://www.php.net/license/3_0.txt The PHP License, Version 3.0
22  * @version   CVS: $Id: timer_example.php 268884 2008-11-12 20:57:49Z clockwerx $
23  * @link       http://pear.php.net/package/Benchmark
24  */
25  
26 require 'Benchmark/Timer.php';
27  
28 /**
29  * Wait
30  *
31  * @param int $amount Amount to wait
32  *
33  * @return void
34  */
35 function wait($amount)
36 {
37     for ($i=0; $i < $amount; $i++) {
38         for ($i=0; $i < 100; $i++) {
39         }
40     }
41 }
42  
43 // Pass the param "true" to constructor to automatically display the results
44 $timer = new Benchmark_Timer();
45 $timer->start();
46 wait(10);
47 $timer->setMarker('Mark1');
48 echo "Elapsed time between Start and Mark1: " .
49       $timer->timeElapsed('Start', 'Mark1') . "\n";
50 wait(50);
51 $timer->stop();
52 $timer->display();
53 ?>

timer

设置几个记号

01 <?php
02  
03 /*
04  * To change this template, choose Tools | Templates
05  * and open the template in the editor.
06  */
07  
08 require 'Benchmark/Benchmark/timer.php';
09 $timer=& new Benchmark_timer(true);
10 $timer->start();
11 //此处可以设置一些代码
12 $timer->setMarker('setup');
13  
14 //此处是更多的已执行代码
15 $timer->setMarker('middle');
16  
17 //此处是更多其他代码
18 $timer->setMarker('done');
19  
20 //最后一点代码
21 $timer->stop();
22  
23 $timer->display();
24  
25 ?>

只有注册用户登录后才能发表评论。
网站导航:

posts - 139, comments - 0, trackbacks - 0, articles - 0

Copyright © PHP博客