不一样的思想~~ http://shop34712791.taobao.com MSN:wins0910@hotmail.com

PHP优化(摘抄)

上一篇 / 下一篇  2008-03-20 22:35:43 / 个人分类:待分析

PHP is a very fast programming language, but there is more to optimizing PHP than just speed of code execution.
php 是一个高效的语言,不过优化php不仅仅是优化程序的代码

In this chapter, we explain why optimizing PHP involves many factors which are not code related, and why tuning PHP requires an understanding of how PHP performs in relation to all the other subsystems on your server, and then identifying bottlenecks caused by these subsystems and fixing them. We also cover how to tune and optimize your PHP scrīpts so they run even faster.

在这篇文章中,我们将揭示为什么优化php包括很多代码没有涉及的因素。和为什么调整php需要理解你的服务器上的所有子系统上PHP的表现并寻找出由这些系统引起的瓶颈并修复他们。当然这也适用于调整和优化你的PHP脚本来使他们运行的更快。

Achieving High Performance
达到高性能

When we talk about good performance, we are not talking about how fast your PHP scrīpts will run. Performance is a set of tradeoffs between scalability and speed. scrīpts tuned to use fewer resources might be slower than scrīpts that perform caching, but more copies of the same scrīpt can be run at one time on a web server.
当我们谈及高性能时,我们不是谈论你的PHP脚本如何的快。性能是在资源占用和速度之间的折中。调整脚本去使用更少的资源会比使用更多的缓存要慢。但是可以有更多的拷贝同时在服务器上运行[就是我们常说的以资源换速度还是以速度换资源—by achieverain]

In the example below, A.php is a sprinter that can run fast, and B.php is a marathon runner than can jog forever at the nearly the same speed. For light loads, A.php is substantially faster, but as the web traffic increases, the performance of B.php only drops a little bit while A.php just runs out of steam.
在下面的例子中,A.php 是一个跑的很快的短跑选手。B.php是一个可以永远跑下去的马拉松选手。在轻量级负载中。A.php绝对领先,但是当网页的流量增加时,B.php的速度仅仅下降了一点,但A.php已经被淘汰了。

Let us take a more realistic example to clarify matters further. Suppose we need to write a PHP scrīpt that reads a 250K file and generates a HTML summary of the file. We write 2 scrīpts that do the same thing: hare.php that reads the whole file into memory at once and processes it in one pass, and tortoise.php that reads the file, one line at time, never keeping more than the longest line in memory. Tortoise.php will be slower as multiple reads are issued, requiring more system calls.
让我们举更过的类似的例子来证明这个事实。假设我们需要写一个读取一个250k大小的文件并生成一个HTML摘要文件。我们同时写两个脚本来做这个事情:hare.php[hare 是兔子的意思 –by achieverain]每次运行直接把整个文件读入内存,tortoise.php[tortoise 是乌龟的意思 –by achieverain]每次只读文件的一行,并且让内存的数据保持在一行。Tortoise.php当然因为因为多次的读取而更慢,需要更多次的系统调用

Hare.php requires 0.04 seconds of CPU and 10 Mb RAM and tortoise.php requires 0.06 seconds of CPU and 5 Mb RAM. The server has 100 Mb free actual RAM and its CPU is 99% idle. Assume no memory fragmentation occurs to simplify things.
hare.php 需要CPU运行0.04秒。10M 内存,tortoise.php 需要CPU运行0.06秒。5M 内存,服务器有100M的空闲物理内存,CPU的空闲资源(idle)为99%.简单起见:假设没有内存碎片。

At 10 concurrent scrīpts running, hare.php will run out of memory (10 x 10 = 100). At that point, tortoise.php will still have 50 Mb of free memory. The 11th concurrent scrīpt to run will bring hare.php to its knees as it starts using virtual memory, slowing it down to maybe half its original speed; each invocation of hare.php now takes 0.08 seconds of CPU time. Meanwhile, tortoise.php will be still be running at its normal 0.06 seconds CPU time.
在10个并发的情况下,hare.php将把所有的内存用完(10 x 10 = 100)。而tortoise.php将还有50M的剩余内存。如果要同时运行第11个 hare.php将是服务器使用虚拟内存,降低的速度也许是原始速度的一般;每次调用hare.php将消耗0.08秒,与此同时,tortoise.php将仍然是0.06秒。
In the table below, the faster php scrīpt for different loads is in bold:
在下面的图表中,不同负载情况下更快的php脚本将被加黑。
Connections
CPU seconds required to satisfy 1 HTTP request
CPU seconds required to satisfy 10 HTTP requests
CPU seconds required to satisfy 11 HTTP requests

hare.php
0.04
0.40
0.88
(runs out of RAM)

tortoise.php
0.06
0.60
0.66

As the above example shows, obtaining good performance is not merely writing fast PHP scrīpts. High performance PHP requires a good understanding of the underlying hardware, the operating system and supporting software such as the web server and database.
由上可知,取得良好的表现并不仅仅是写一个高速的php脚本。高性能的PHP需要很好的理解程序所基于的硬件基础,操作系统,web server [如apache]和数据库之类的支援软件

Bottlenecks
瓶颈

The hare and tortoise example has shown us that bottlenecks cause slowdowns. With infinite RAM, hare.php will always be faster than tortoise.php. Unfortunately, the above model is a bit simplistic and there are many other bottlenecks to performance apart from RAM:
刚才那个例子给我们展示了瓶颈的存在导致速度降低,如果有无限的内存,hare.php将永远比tortoise.php跑的快。不幸的是,上面的有点太单纯了,而且很多其他的瓶颈也在蚕食着内存。

(a) Networking
(a)网络

Your network is probably the biggest bottleneck. Let us say you have a 10 Mbit link to the Internet, over which you can pump 1 megabyte of data per second. If each web page is 30k, a mere 33 web pages per second will saturate the line.
你的网络情况也许会是一个最大的瓶颈。假设服务器带宽10Mbit那么你每秒能传输大约1Mbyte数据。如果每个网页30K,那么你每秒最多传输33个网页。
More subtle networking bottlenecks include frequent access to slow network services such as DNS, or allocating insufficient memory for networking software.
更多在网络不佳时导致访问速度降低的原因有DNS或者内存不足等。
(b) CPU
(b) CPU

If you monitor your CPU load, sending plain HTML pages over a network will not tax your CPU at all because as we mentioned earlier, the bottleneck will be the network. However for the complex dynamic web pages that PHP generates, your CPU speed will normally become the limiting factor. Having a server with multiple processors or having a server farm can alleviate this.
如果你控制你的CPU负载。发送一个无格式的HTML页基本不占用你的CPU资源。然而一个完全由PHP生成的动态页会占用很多CPU资源。多CPU服务器或者服务器集群可以缓解这个问题。

(c) Shared Memory
(c) 共享内存

Shared memory is used for inter-process communication, and to store resources that are shared between multiple processes such as cached data and code. If insufficient shared memory is allocated any attempt to access resources that use shared memory such as database connections or executable code will perform poorly.
共享内存是为进程间通讯准备的,如果系统内存不足的话,使用共享内存的操作如 数据库联接,执行代码将会是低效的。
(d) File System
(d) 文件系统

Accessing a hard disk can be 50 to 100 times slower than reading data from RAM. File caches using RAM can alleviate this. However low memory conditions will reduce the amount of memory available for the file-system cache, slowing things down. File systems can also become heavily fragmented, slowing down disk accesses. Heavy use of symbolic links on Unix systems can slow down disk accesses too.
访问硬盘比访问内存要慢50到100倍。将文件缓存存入内存可以解决这个问题。但是服务器内存会被文件缓存的数据大量占用,反而将系统速度减慢。严重的文件碎片也会降低访问硬盘的速度,在Unix系统上大量使用符号链接也会降低访问硬盘的速度

Default Linux installs are also notorious for setting hard disk default settings which are tuned for compatibility and not for speed. Use the command hdparm to tune your Linux hard disk settings.
默认设置下安装的linux有个糟糕的问题就是硬盘的设置是兼容性优先而不是速度。使用 hdparm 这个命令可以调整你的linux硬盘的设置
(e) Process Management
(e) 进程管理

On some operating systems such as Windows creating new processes is a slow operation. This means CGI applications that fork a new process on every invocation will run substantially slower on these operating systems. Running PHP in multi-threaded mode should improve response times (note: older versions of PHP are not stable in multi-threaded mode).
在windows等的操作系统中建立一个新的进程是个缓慢的操作。这意味着CGI软件在这些系统上的调用是缓慢的。在多线程模式下运行PHP可以加快速度(注意:老版本的PHP不支持多线程模式)

Avoid overcrowding your web server with too many unneeded processes. For example, if your server is purely for web serving, avoid running (or even installing) X-Windows on the machine. On Windows, avoid running Microsoft Find Fast (part of Office) and 3-dimensional screen savers that result in 100% CPU utilization.
避免你的服务器被过多没有必要的进程所拥塞。例如:假如你的服务器纯粹用于网站服务,不在服务器上运行(甚至安装)X-Windows,在windows上,不运行Microsoft Find Fast (part of Office)和3D屏保可以防止100%CPU的情况

Some of the programs that you can consider removing include unused networking protocols, mail servers, antivirus scanners, hardware drivers for mice, infrared ports and the like. On Unix, I assume you are accessing your server using SSH. Then you can consider removing:

deamons such as telnetd, inetd, atd, ftpd, lpd, sambad
sendmail for incoming mail
portmap for NFS
xfs, fvwm, xinit, X

You can also disable at startup various programs by modifying the startup files which are usually stored in the /etc/init* or /etc/rc*/init* directory.

Also review your cron jobs to see if you can remove them or reschedule them for off-peak periods.

(f) Connecting to Other Servers

一些你可以考虑移除的网络控制软件,邮件服务器,杀毒软件,鼠标驱动,红外驱动等等一些.在Unix上,我认为你是通过SSH访问的网站.那么你就可以考虑移除一些像  
telnetd, inetd, atd, ftpd, lpd, sambad
sendmail for incoming mail
portmap for NFS
xfs, fvwm, xinit, X
之类的服务,你也可以考虑仅用一些启动时加载的项目.你可以通过修改 /etc/init* 或/etc/rc*/init*的启动配置文件来实现他们的配置.你一个可以看下你的计划任务,不需要的就移除,需要执行的就把他放在没人访问服务器的时候执行.

If your web server requires services running on other servers, it is possible that those servers become the bottleneck. The most common example of this is a slow database server that is servicing too many complicated SQL requests from multiple web servers.
如果你的服务器需要一些在其他服务器上运行的服去.这也许也会成为一个瓶颈.最常见的例子就是一个缓慢的或者被过多连接拥塞的数据库服务器

When to Start Optimizing?
什么时候开始优化?

Some people say that it is better to defer tuning until after the coding is complete. This advice only makes sense if your programming team's coding is of a high quality to begin with, and you already have a good feel of the performance parameters of your application. Otherwise you are exposing yourselves to the risk of having to rewrite substantial portions of your code after testing.
一些人说最好推迟到代码完成之后.这个建议指挥令你感觉到你的程序员团队有高质量的代码,你已经对你的程序表现十分满意.否则就是你认为你将在测试之后重写你的部分代码

My advice is that before you design a software application, you should do some basic benchmarks on the hardware and software to get a feel for the maximum performance you might be able to achieve. Then as you design and code the application, keep the desired performance parameters in mind, because at every step of the way there will be tradeoffs between performance, availability, security and flexibility.

我的建议是在你设计一个程序之前,你就应该做一些你可以做到的能够提升性能的基准。然后你开始设计软件的代码。在脑子里时刻想着这些准则,因为每一步设计都有可能是你在性能,实用性,安全性,易用性的折中方案。

Also choose good test data. If your database is expected to hold 100,000 records, avoid testing with only a 100 record database – you will regret it. This once happened to one of the programmers in my company; we did not detect the slow code until much later, causing a lot of wasted time as we had to rewrite a lot of code that worked but did not scale.

选择良好的测试用数据。如果你的数据库将要承载100,000条记录,避免使用只有100条记录的数据库进行测试–这样会让你后悔的.这种事情曾经在我所在的公司的一个程序员身上发生过:我们没有发现导致缓慢的代码.直到很久以后,程序执行消耗了大量时间.我们不得不重写达赖能够的数据.

Tuning Your Web Server for PHP
为PHP调整你的服务器

We will cover how to get the best PHP performance for the two most common web servers in use today, Apache 1.3 and IIS. A lot

of the advice here is relevant for serving HTML also.
接下来我们谈谈如何在现今最流行的两个网络服务器平台 Apache 和 IIS 上让PHP取得最好的的表现。这里也有很多关于HTML的建议(??)

The authors of PHP have stated that there is no performance nor scalability advantage in using Apache 2.0 over Apache 1.3

with PHP, especially in multi-threaded mode. When running Apache 2.0 in pre-forking mode, the following discussion is still

relevant (21 Oct 2003).
PHP的作者统计过PHP在 Apache 2.0 上的表现比apache 1.3 上的表现在实际上并没有实质的优势,尤其在多线程模式下。当在apache 2.0的预

编译模式下运行。他们的讨论结果也是类似的

(a) Apache 1.3/2.0
(a) Apache 1.3/2.0

Apache is available on both Unix and Windows. It is the most popular web server in the world. Apache 1.3 uses a pre-forking

model for web serving. When Apache starts up, it creates multiple child processes that handle HTTP requests. The initial

parent process acts like a guardian angel, making sure that all the child processes are working properly and coordinating

everything. As more HTTP requests come in, more child processes are spawned to process them. As the HTTP requests slow down,

the parent will kill the idle child processes, freeing up resources for other processes. The beauty of this scheme is that it

makes Apache extremely robust. Even if a child process crashes, the parent and the other child processes are insulated from

the crashing child.

Apache 在Unix和Windows都可以使用。他是世界上最流行的网络服务器。apache为网络服务使用了预编译模式(pre-forking model)。当

apache启动时。他创建了多个等待http请求的子进程。最初的父进程(parent process)就像个守护天使,他保证那些子进程在正常工作。当出现

更多的HTTP请求时,更多的子进程被创建。当HTTP请求减少时,空闲的子进程就会被结束,他们(子进程)占用的资源也将会被释放。这种完美

的配置使Apache高效的运行。甚至当一个子进程崩溃时,父进程将把它和其他子进程隔离。
The pre-forking model is not as fast as some other possible designs, but to me that it is "much ado about nothing" on a

server serving PHP scrīpts because other bottlenecks will kick in long before Apache performance issues become significant.

The robustness and reliability of Apache is more important.
预编译模式并不比其他一些必要的设计/实现更快。但是对于我们来说在其他瓶颈影响apache性能之前这个是非常简单的。apache的稳定和可靠

是更重要的。

Apache 2.0 offers operation in multi-threaded mode. My benchmarks indicate there is little performance advantage in this

mode. Also be warned that many PHP extensions are not compatible (e.g. GD and IMAP). Tested with Apache 2.0.47 (21 Oct 2003).
apache 2.0 提供在多线程模式的操作。我的测试显示在这个模式下的性能只有一点点的提升。当然要提醒一下:很多PHP扩展不被兼容。

Apache is configured using the httpd.conf file. The following parameters are particularly important in configuring child

processes:

APACHE 使用httpd.conf作为配置文件。下面的这些对配置子进程非常重要

Directive
Default
Descrīption

MaxClients
256
The maximum number of child processes to create. The default means that up to 256 HTTP requests can be handled concurrently.

Any further connection requests are queued.

StartServers
5
The number of child processes to create on startup.

MinSpareServers
5
The number of idle child processes that should be created. If the number of idle child processes falls to less than this

number, 1 child is created initially, then 2 after another second, then 4 after another second, and so forth till 32 children

are created per second.

MaxSpareServers
10
If more than this number of child processes are alive, then these extra processes will be terminated.

MaxRequestsPerChild
0
Sets the number of HTTP requests a child can handle before terminating. Setting to 0 means never terminate. Set this to a

value to between 100 to 10000 if you suspect memory leaks are occurring, or to free under-utilized resources.

For large sites, values close to the following might be better:

MinSpareServers 32

MaxSpareServers 64

对于大型网站。建议按照以下的数值进行配置

MinSpareServers 32

MaxSpareServers 64

Apache on Windows behaves differently. Instead of using child processes, Apache uses threads. The above parameters are not

used. Instead we have one parameter: ThreadsPerChild which defaults to 50. This parameter sets the number of threads that can

be spawned by Apache. As there is only one child process in the Windows version, the default setting of 50 means only 50

concurrent HTTP requests can be handled. For web servers experiencing higher traffic, increase this value to between 256 to

1024.
apache在windows上的表现不同。apache在windows使用上使用线程(threads).上面的那些参数将不会被使用。作为替代的是我们使用一个参数

:ThreadsPerChild (默认数值为50)由于在windows版本上只有一个子进程,默认设为50意味着只有50个http并发请求。大流量的服务器请把

这个数值提升到256至1024。<

Other useful performance parameters you can change include:
其他一些你应该修改的有用参数
Directive
Default
Descrīption

SendBufferSize
Set to OS default
Determines the size of the output buffer (in bytes) used in TCP/IP connections. This is primarily useful for congested or

slow networks when packets need to be buffered; you then set this parameter close to the size of the largest file normally

downloaded. One TCP/IP buffer will be created per client connection.

KeepAlive [on|off]
On
In the original HTTP specification, every HTTP request had to establish a separate connection to the server. To reduce the

overhead of frequent connects, the keep-alive header was developed. Keep-alives tells the server to reuse the same socket

connection for multiple HTTP requests.

If a separate dedicated web server serves all images, you can disable this option. This technique can substantially improve

resource utilization.

KeepAliveTimeout
15
The number of seconds to keep the socket connection alive. This time includes the generation of content by the server and

acknowledgements by the client. If the client does not respond in time, it must make a new connection.

This value should be kept low as the socket will be idle for extended periods otherwise.

MaxKeepAliveRequests
100
Socket connections will be terminated when the number of requests set by MaxKeepAliveRequests is reached. Keep this to a

high value below MaxClients or ThreadsPerChild.

TimeOut
300
Disconnect when idle time exceeds this value. You can set this value lower if your clients have low latencies.

LimitRequestBody
0
Maximum size of a PUT or POST. O means there is no limit.

If you do not require DNS lookups and you are not using the htaccess file to configure Apache settings for individual

directories you can set:

# disable DNS lookups: PHP scrīpts only get the IP address

HostnameLookups off

# disable htaccess checks

<Directory />

AllowOverride none

</Directory>

If you are not worried about the directory security when accessing symbolic links, turn on FollowSymLinks and turn off

SymLinksIfOwnerMatch to prevent additional lstat() system calls from being made:

Options FollowSymLinks

#Options SymLinksIfOwnerMatch

(b) IIS Tuning
(b) IIS 调整
IIS is a multi-threaded web server available on Windows NT and 2000. From the Internet Services Manager, it is possible to

tune the following parameters:
IIS 是一个在 Windows NT 和 2000上运行的多线程网络服务器。通过IIS管理器,他可以调整以下的参数:
Performance Tuning based on the number of hits per day.
Determines how much memory to preallocate for IIS. (Performance Tab).

Bandwidth throttling
Controls the bandwidth per second allocated per web site. (Performance Tab).

Process throttling
Controls the CPU% available per Web site. (Performance Tab).

Timeout
Default is 900 seconds. Set to a lower value on a Local Area Network. (Web Site Tab)

HTTP Compression
HTTP 压缩
In IIS 5, you can compress dynamic pages, html and images. Can be configured to cache compressed static html and images. By

default compression is off.
在IIS 5,你可以压缩动态页,html页和图片。他可以被配置为缓存静态页和图片。默认情况下压缩是关闭的

HTTP compression has to be enabled for the entire physical server. To turn it on open the IIS console, right-click on the

server (not any of the subsites, but the server in the left-hand pane), and get Properties. Click on the Service tab, and

select "Compress application files" to compress dynamic content, and "Compress static files" to compress static content.

You can also configure the default isolation level of your web site. In the Home Directory tab under Application Protection,

you can define your level of isolation. A highly isolated web site will run slower because it is running as a separate

process from IIS, while running web site in the IIS process is the fastest but will bring down the server if there are

serious bugs in the web site code. Currently I recommend running PHP web sites using CGI, or using ISAPI with Application

Protection set to high.
你也可以单独编辑你的网站的等级。在网站管理的根目录的标签上,你可以单另定义你的等级。由于他运行在一个单独的进程下,高度自定义

等级的网站会慢一些。尽管在IIS上运行网站一般很快,但是当代码有缺陷的时候会减慢网站的运行速度。我强烈建议PHP以CGI方式在IIS上运

行,或者当以ISAPI模式运行时使用高等级。

You can also use regedit.exe to modify following IIS 5 registry settings stored at the following location:
你也可以使用 regedit.exe 直接编辑IIS 5 在注册表中的信息,他的位置是:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Inetinfo\Parameters\

MemCacheSize
内存缓存大小
Sets the amount of memory that IIS will use for its file cache. By default IIS will use 50% of available memory. Increase if

IIS is the only application on the server. Value is in megabytes.
当IIS使用文件缓存的时候设置他使用内存的大小。默认情况下IIS将使用50%可使用的内存。只有当IIS是服务器上唯一的网络服务器的时候将

会增长占用的内存。他增长的数量单位是MB

MaxCachedFileSize
Determines the maximum size of a file cached in the file cache in bytes. Default is 262,144 (256K).

ObjectCacheTTL
Sets the length of time (in milliseconds) that objects in the cache are held in memory. Default is 30,000 milliseconds (30

seconds).

MaxPoolThreads
Sets the number of pool threads to create per processor. Determines how many CGI applications can run concurrently. Default

is 4. Increase this value if you are using PHP in CGI mode.

ListenBackLog
Specifies the maximum number of active Keep Alive connections that IIS maintains in the connection queue. Default is 15, and

should be increased to the number of concurrent connections you want to support. Maximum is 250.

If the settings are missing from this registry location, the defaults are being used.
如果设置错了。服务器就会使用默认数值。

High Performance on Windows: IIS and FastCGI
在windows上高效的 :IIS 和 FastCGI

After much testing, I find that the best PHP performance on Windows is offered by using IIS with FastCGI. CGI is a protocol

for calling external programs from a web server. It is not very fast because CGI programs are terminated after every page

request. FastCGI modifies this protocol for high performance, by making the CGI program persist after a page request, and

reusing the same CGI program when a new page request comes in.
在多次测试之后,我发现在windows上PHP表现最好的情况是以 FastCGI方式在IIS上运行(我个人持保留意见—by achieverain)。CGI是网络服

务器调用扩展程序的一个协议。他由于每个页面请求结束之后都回停止而不是很快。FastCGI是一种高效的协议。当出现重复的页面请求的时候

他会恢复并返回一个相同的页面执行的结果。

As the installation of FastCGI with IIS is complicated, you should use the EasyWindows PHP Installer. This will install PHP,

FastCGI and Turck MMCache for the best performance possible. This installer can also install PHP for Apache 1.3/2.0.
以FastCGI 方式安装到IIS上是很复杂的,你必须使用EasyWindows PHP Installer。他将把PHP, FastCGI 和 Turck MMCache以最优化的方式安

装好。这个安装包也可以给Apache 1.3/2.0安装PHP。(因为这是比较古老的文章[2005年],我实际使用中发现EasyWindows PHP Installer并不

是万灵丹,还是自己老老实实调整吧 —by achieverain)
This section on FastCGI added 21 Oct 2003.

PHP4's Zend Engine
PHP4的 Zend 引擎
The Zend Engine is the internal compiler and runtime engine used by PHP4. Developed by Zeev Suraski and Andi Gutmans, the

Zend Engine is an abbreviation of their names. In the early days of PHP4, it worked in the following fashion:
Zend引擎是PHP4使用的内部编译器和运行用引擎,他是由Zeev Suraski 和 Andi Gutmans开发。zend引擎是他们名字的混合体。在PHP4的早期

,他是以下方式运行的:

The PHP scrīpt was loaded by the Zend Engine and compiled into Zend opcode. Opcodes, short for operation codes, are low level

binary instructions. Then the opcode was executed and the HTML generated sent to the client. The opcode was flushed from

memory after execution.
PHP脚本被Zend引擎读取并被编译成Zend中间代码,中间代码比操作代码短,比二进制描述要低级。然后中间代码会被执行,Html被生成并发送

到客户端。在执行完毕之后中间代码就被从内存中清除。

Today, there are a multitude of products and techniques to help you speed up this process. In the following diagram, we show

the how modern PHP scrīpts work; all the shaded boxes are optional.
现在,有很多产品和技术帮助你加速这个过程。在以下的简述中,我们将展现当代PHP的工作方式,所有隐藏的技巧将被展现。

PHP scrīpts are loaded into memory and compiled into Zend opcodes. These opcodes can now be optimized using an optional

peephole optimizer called Zend Optimizer. Depending on the scrīpt, it can increase the speed of your PHP code by 0-50%.
PHP脚本读入内存并被编译成Zend的中间代码。这些中间代码将被一个内置解析器: Zend Optimizer 优化。通过这些步骤,他可以提高你的程

序0-50%的执行速度

Formerly after execution, the opcodes were discarded. Now the opcodes can be optionally cached in memory using several

alternative open source products and the Zend Accelerator (formerly Zend Cache), which is a commercial closed source product.

The only opcode cache that is compatible with the Zend Optimizer is the Zend Accelerator. An opcode cache speeds execution by

removing the scrīpt loading and compilation steps. Execution times can improve between 10-200% using an opcode cache.
原本在执行结束之后,中间代码将被清除。但现在使用一些开源代码和 Zend Accelerator(原生的zend缓存,虽然不是个开源软件)
Where to find Opcode Caches
哪里可以找到中间代码的缓存

Zend Accelerator: A commercial opcode cache developed by the Zend Engine team. Very reliable and robust. Visit

http://zend.comfor more information.
Zend Accelerator: 一个由Zend 引擎团队开发的商业缓存。非常可靠和稳定。你可以访问http://zend.com去得到相关信息。

You will need to test the following open source opcode caches before using them on production servers as their performance

and reliability very much depends on the PHP scrīpts you run.
你要在部署以下开源缓存之前详细测试他们。因为他们的稳定性和速度很依赖于你的PHP脚本。

Turcke MMCache:http://turck-mmcache.sourceforge.net/is no longer maintained. See eAccelerator, which is a branch of mmcache

that is actively maintained (Added 28 Feb 2005).

Alternative PHP Cache:http://apc.communityconnect.com/

PHP Accelerator:http://www.php-accelerator.co.uk/

AfterBurner Cache:http://www.bwcache.bware.it/

One of the secrets of high performance is not to write faster PHP code, but to avoid executing PHP code by caching generated

HTML in a file or in shared memory. The PHP scrīpt is only run once and the HTML is captured, and future invocations of the

scrīpt will load the cached HTML. If the data needs to be updated regularly, an expiry value is set for the cached HTML. HTML

caching is not part of the PHP language nor Zend Engine, but implemented using PHP code. There are many class libraries that

do this. One of them is the PEAR Cache, which we will cover in the next section. Another is the Smarty template library.
一个取得高性能的秘密就是不要写过快的程序,但是要避免在文件缓存或者在共享内存中生成HTML。PHP脚本只是在HTML被捕获的时候运行一次

,之后的调用PHP就会读取缓存的HTML。如果数据需要经常改变。缓存的HTML就需要设置一个失效时间。HTML缓存并不是PHP语言或Zend引擎中

的一部分,但可以用PHP实现。现在有很多的类库可以做这个。其中一个就是PEAR 缓存。另一个是Smarty 模版库
Finally, the HTML sent to a web client can be compressed. This is enabled by placing the following code at the beginning of

your PHP scrīpt:
最后,发送到客户端的HTML可以被压缩。这需要你在PHP代码的开始加上以下的代码
<?php

ob_start("ob_gzhandler");

:
:

?>

If your HTML is highly compressible, it is possible to reduce the size of your HTML file by 50-80%, reducing network

bandwidth requirements and latencies. The downside is that you need to have some CPU power to spare for compression.
如果你的HTML被高度压缩,他可能将你的HTML减少50-80%的体积。这可以节省网络带宽和减少数据延迟,而代价仅仅是增加少量的CPU占用。
HTML Caching with PEAR Cache
PEAR Cache中的HTML缓存
The PEAR Cache is a set of caching classes that allows you to cache multiple types of data, including HTML and images.
PEAR Cache是一个允许包括HTML和图片在内多种类型数据的缓存类。

The most common use of the PEAR Cache is to cache HTML text. To do this, we use the Output buffering class which caches all

text printed or echoed between the start() and end() functions:
PEAR Cache最常见的使用便是缓存HTML文本。我们可以在输出缓存类使用start() 和 end()输出所有缓存的数据。

require_once("Cache/Output.php");

$cache = new Cache_Output("file", array("cache_dir" => "cache/") );

if ($contents = $cache->start(md5("this is a unique key!"))) {

#
# aha, cached data returned
#

  print $contents;
  print "<p>Cache Hit</p>";

} else {

#
# no cached data, or cache expired
#

  print "<p>Don't leave home without it…</p>"; # place in cache
  print "<p>Stand and deliver</p>"; # place in cache
  print $cache->end(10);

}

Since I wrote these lines, a superior PEAR cache system has been developed: Cache Lite; and for more sophisticated

distributed caching, see memcached (Added 28 Feb 2005).
当我们写下这些代码之后,一个超级PREA缓存系统就被开发出来了:缩水版缓存;如果需要复杂的缓存,看看memcached 。
The Cache constructor takes the storage driver to use as the first parameter. File, database and shared memory storage

drivers are available; see the pear/Cache/Container directory. Benchmarks by Ulf Wendel suggest that the "file" storage

driver offers the best performance. The second parameter is the storage driver options. The options are "cache_dir", the

location of the caching directory, and "filename_prefix", which is the prefix to use for all cached files. Strangely enough,

cache expiry times are not set in the options parameter.
缓存创建的第一个参数是存储的路径,文件,数据库,共享内存都可以;看看pear/Cache/Containe的路径。Ulf Wendel的测试指出“文件”存

储提供了最好的性能,第二个参数是存储的选项。这个选项是"cache_dir",存储缓存的路径;filename_prefix:所有缓存文件名字的前缀。

很奇怪,缓存失效时间并不在这些参数里设置。

To cache some data, you generate a unique id for the cached data using a key. In the above example, we used md5("this is a

unique key!").
为缓存以下数据,你需要为缓存数据生成唯一ID。在上面的例子中,我们使用了d5("this is a unique key!")
The start() function uses the key to find a cached copy of the contents. If the contents are not cached, an empty string is

returned by start(), and all future echo() and print() statements will be buffered in the output cache, until end() is

called.
start()函数生成一个key以寻找缓存的内容的拷贝。如果内容没有被缓存,start()将返回一个空字符串,当调用end()时所有的输出将会被写

进缓存。
The end() function returns the contents of the buffer, and ends output buffering. The end() function takes as its first

parameter the expiry time of the cache. This parameter can be the seconds to cache the data, or a Unix integer timestamp

giving the date and time to expire the data, or zero to default to 24 hours.
end()函数返回并输出缓冲中的数据。end()函数的第一个参数就是失效时间,这个参数可以设置数据的秒(后失效)或者失效的Unix时间戳,或

者默认的0(即24小时);
Another way to use the PEAR cache is to store variables or other data. To do so, you can use the base Cache class:
另一个使用PREA缓存的方式是存储变量和其他数据。为实现这个目标,你可以使用基础的缓存类:

<?php

require_once("Cache.php");

$cache = new Cache("file", array("cache_dir" => "cache/") );
$id = $cache->generateID("this is a unique key");

if ($data = $cache->get($id)) {

  print "Cache hit.<br>Data: $data";

} else {

  $data = "The quality of mercy is not strained…";
  $cache->save($id, $data, $expires = 60);
  print "Cache miss.<br>";

}

?>

To save the data we use save(). If your unique key is already a legal file name, you can bypass the generateID() step.

Objects and arrays can be saved because save() will serialize the data for you. The last parameter controls when the data

expires; this can be the seconds to cache the data, or a Unix integer timestamp giving the date and time to expire the data,

or zero to use the default of 24 hours. To retrieve the cached data we use get().
为了存储这些数据我们将使用save(),如果你的唯一ID已经生成,你可以跳过生成ID这一步。因为save()序列化了数据,所以他可以存储类和

数组。最后一个参数控制着数据的实效时间;这个可以是缓存数据的失效秒数。或者UNIX时间戳。或者默认的24小时。重新取得这些缓存过的

数据我们使用get()函数。

You can delete a cached data item using $cache->delete($id) and remove all cached items using $cache->flush().
你可以使用$cache->delete($id)删除一个缓存过的数据,使用$cache->flush()删除所有缓存。
New: A faster Caching class is Cache-Lite. Highly recommended.
提示:一个更快的缓存类是Cache-Lite,高度推荐。
Using Benchmarks
使用测试

In earlier section we have covered many performance issues. Now we come to the meat and bones, how to go about measuring and

benchmarking your code so you can obtain decent information on what to tune.
在前面的部分我们谈论了很多方便的性能。现在我们上正餐吧,如何测试你的代码的性能以使你取得如何调整的信息。


相关阅读:

TAG: 待分析

 

评分:0

我来说两句

Open Toolbar