Exploration of PHP program acceleration

Source: Internet
Author: User
Tags ereg http cookie time 0
-(1) introduction-(2) Do I need acceleration? -(3) how to accelerate? -1 Test ◆ server load test apache ◆ script execution speed test PEAR :: benchmark-2 acceleration ◆ code optimization ◆ compressed output Gzip ◆ content cache output PEARContentcache ◆ function cache output PEARFunctioncache ◆ acceleration tools-(a) Introduction
-(2) is acceleration required?
-(3) how to accelerate?
-<1> test
◆ Server load test apache.pdf
◆ Script execution speed test PEAR: Benchmark
-<2> Acceleration
◆ Code optimization
◆ Compressed output Gzip
◆ Content cache output PEAR Content cache
◆ Function cache output PEAR Function cache
◆ Acceleration tool software APC, Turck MMCache, PHPA, Zend Performance Suite
-(IV) summary

(1) Introduction

This article attempts to explore various aspects of PHP program acceleration, including the necessity and specific measures taken from different perspectives. Hope to help readers understand the PHP program acceleration and apply it to reality.

(2) is acceleration required?

It sounds silly. In this era, few people doubt that time is the most valuable asset, especially in the commercial market. The faster the program runs, the more time the user saves. in this way, your program can use less time and server resources to serve the user, thus generating more benefits.
I think for most people (including myself), many WEB projects have been completed in a very short time and are usually not carefully considered and strictly tested. Start a new WEB project. Many people are building fast and messy applications and lack the necessary time to adjust and improve code. Optimization and acceleration are the measures we must take.
However, not all programs require acceleration.
It is a waste of time to optimize the completed code. The best way is to pay attention to the efficiency when writing the code. after the project is completed, only the part that needs to be optimized is optimized. Generally, a program only has a few bottlenecks that affect the speed. you can find and solve them to run the program well. In addition, when the execution efficiency is low, we should first look at the overall situation to find out the main factors that affect the efficiency, rather than sticking to the details-for example, the data volume is too large and the server bandwidth is insufficient, or the hardware configuration is too low. in this case, optimization code is useless.
In addition, when there are no obvious signs of slow execution in the program, do not be too picky. it is a waste of time to improve some very detailed code. With this time, you can complete another project or complete an extension function for the original project. Of course, you can joke that I am not responsible enough to do my job well. I can also say that you are a perfectionist :-)
In summary, before you decide to speed up your PHP program, ask yourself if it is necessary.

(3) how to accelerate?

Before answering the question "how to accelerate", you need to answer the following two questions:
Where is your program slow?
Which of the following aspects can PHP accelerate?
Obviously, I cannot give you the answer to the first small question, but I suggest you use the "test script execution speed" method to solve it. How to solve this problem can be considered only by identifying the bottleneck that limits the speed.
The second small question is my approximate answer: code optimization, compression output, content cache output, function cache output, and acceleration/cache tool software. If you know more, please let me know :-)
Next, let's take a detailed look at the relevant technologies in these aspects. Of course, there are countless details in every aspect to discuss. the following content will inevitably be one-sided. please add it.

<1> test
◆ Server load test


It is also common that the server load is too large and the program efficiency is affected. we need to test this. Here I take the most common Apache server as an example.
The Apache server comes with a tool named AB (apacheworkflow) in the bin directory. With this lightweight tool, we can test the server load to see how the server performs under heavy loads. Apache can simulate continuous online requests for a specific URL, and simulate online requests with the same number of points at the same time, therefore, the use of apachetings can help us simulate the actual launch possible conditions during website development, and use the simulation data as the basis for adjusting server settings or programs.
Output in the command line:

./AB-n number_of_total_requests \
-C number_of_simultaneous_requests \
Http: // your_web_server/your_php_app.php

For example:

./AB-n 1000-c 50 http://www.domain.com/myapp.php

At the same time, AB will send 50 concurrent requests to http://www.domain.com/myapp.php, with a total of requests.
The test results may be as follows:

Server Software: Apache/2.0.16
Server Hostname: localhost
Server Port: 80
Document Path:/myapp. php
Document Length: 1311 bytes
Concurrency Level: 50
Time taken for tests: 8.794 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 1754000 bytes
HTML transferred: 1311000 bytes
Requests per second: 113.71
Transfer rate: 199.45 kb/s converted Ed
Connection Times (MS)
Min avg max
Connect: 0 0 5
Processing: 111 427 550
Total: 111 427 555

Myapp. php processes 113.71 requests per second. Increase the number of requests to see if the server can handle more pressure. You also need to adjust parameters such as MaxClients, ThreadsPerChild, and MaxThreadsPerChild of Apache based on the MPM module in your httpd. conf file.
If you want more detailed information, go to www.apache.org for more in-depth documents, including modules and third-party efficiency improvement tools. After modifying httpd. conf, restart the Apache server and then use AB for testing. The number of requests per second increases or decreases.
Write down the parameters each time, and finally select the configuration with the best efficiency.
Besides AB, we also have many excellent server performance testing software. In addition, if your server is not Apache, please find a test method by yourself.

◆ Script execution speed test

As mentioned above, we can only optimize the code that affects the speed. The Benchmark_Timer class and Benchmark_Iterate class in the benchmark package of PEAR can be used to conveniently test the speed of script execution. (For installation and configuration of PEAR, please view relevant information)
First, use the Benchmark_Iterate class to test the execution time of a function or method of a class in the program.

Benchmark1.php


Require_once ('benchmark/Iterate. php ');
$ Benchmark = new Benchmark_Iterate ();

$ Benchmark-> run (10, 'myfunction', 'test ');
$ Result = $ benchmark-> get ();
Echo"

"; Print_r ($ result); echo"
";
Exit;

Function myFunction ($ var ){
// Do something
Echo 'hello ';
}

?>

Create the benchmark Iterate object $ benchmark, which is used to execute the myFunction for 10 times.
The $ argument variable is passed to myFunction each time. the analysis results run multiple times are saved to $ result, and then obtained using the get () method of the benchmark object. This result is output to the screen using print_r. The following results are usually output:
Hello
Array ([1] => 0.000427 [2] => 0.000079 [3] => 0.000072 [4] => 0.000071 [5] => 0.000076 [6] => 0.000070 [7] => 0.000073 [8] => 0.000070 [9] => 0.000074 [10] => 0.000072 [mean] => 0.000108 [iterations] => 10) every execution of myFunction, the benchmark object tracks the execution time. And calculates the average execution time (the line [mean ). By running the target function multiple times, you can obtain the average running time of the function.
In actual tests, the number of functions should be at least 1000 times, so that objective results can be obtained.

Now let's take a look at another method to test the script running time-use the Benchmark_Timer class to test the time consumed by code execution and the time between each call and the next call in the code.

Benchmark2.php

Require_once 'benchmark/Timer. php ';
$ Timer = new Benchmark_Timer ();
$ Timer-> start ();
$ Timer-> setMarker ('start _ myfunction ');

For ($ I = 0; $ I <10; $ I ++ ){
MyFunction ($ argument );
}
$ Timer-> setMarker ('end _ myfunction ');
$ Timer-> stop ();
$ Profiling = $ timer-> getProfiling ();

Echo'
Time elapsed :'.
$ Timer-> timeElapsed ('start _ myfunction', 'end _ myfunction ').'
';
Echo'
'; Print_r ($ profiling); echo'
';
Exit;

Function myFunction ($ var ){
Static $ counter = 0;
// Do something
Echo $ counter ++ .'';
}
?>


First, create a benchmark timer object $ timer. Call the start () method to start timing. The SetMaker () method is used to mark the code segment to be tested. The MyFunction () function is called in a loop to indicate the code to be executed (of course, it is not that simple in practice ). Then, use the setMarker () method of the $ timer object to mark the end point of the program execution. GetProfiling () is used to obtain the analysis information. The time consumed by program execution between two tags is calculated using the timeElapsed () method (like the loop in the example ). Finally, use print_r () to output the information to the screen:
Array ([0] => Array ([name] => Start [time] => 1085730111.27175200 [diff] =>-[total] => 1085730111.271752) [1] => Array ([name] => start_myFunction [time] => 1085730111.27203800 [diff] => 0.000286 [total] => 1085730111.272038) [2] => Array ([name] => end_myFunction [time] => 1085730111.27263200 [diff] => 0.000594 [total] => 1085730111.272632) [3] => Array ([name] => Stop [time] => 1085730111.27271800 [diff] => 0.000086 [total] => 1085730111.272718 )) 0 1 2 3 4 5 6 7 8 9
Time elapsed: 0.000594

In this way, you can set a large number of time period tags in the code to obtain the time consumed during code execution, it is easy to see which part of the code affects the running efficiency of the entire program. Then begin to improve this part of the code.
With the above two methods, you can find out some of the code that most affects the speed. It can also be used to test the optimized code to see how fast the execution speed has been improved. Test-> optimization-> Test-> optimization... In this way, you can finally determine the code that provides the best efficiency.

<2> Acceleration

◆ Code optimization
PEAR: BenchMark. now you know how to test your code and how to judge which part of your code is slow. Next I will talk about how to eliminate or optimize the slow code.
In this regard, my main experience is only two points. one is to eliminate incorrect or inefficient loops, and the other is to optimize database query statements. There are some other optimization details, such as "str_replace faster than ereg_replace" and "echo faster than print. These are all put aside for the moment. later I will mention using cache to deal with too frequent IO.
Next we will compare the efficiency (consumed time) of the three functions with the same functions but different programming languages.

Badloops. php

Require_once ('benchmark/Iterate. php ');
Define ('max _ run', 100 );
$ Data = array (1, 2, 3, 4, 5 );

DoBenchmark ('v1 ', $ data );
DoBenchmark ('V2', $ data );
DoBenchmark ('v3 ', $ data );
Function doBenchmark ($ functionName = null, $ arr = null)
{
Reset ($ arr );
$ Benchmark = new Benchmark_Iterate;
$ Benchmark-> run (MAX_RUN, $ functionName, $ arr );
$ Result = $ benchmark-> get ();
Echo'
';
Printf ("% s ran % d times where average exec time %. 5f ms ", $ functionName, $ result ['iterations '], $ result ['Mean'] * 1000 );
}

Function v1 ($ myArray = null ){
// Cycle with poor efficiency
For ($ I = 0; $ I <sizeof ($ myArray); $ I ++)
{
Echo' ';
}
}

Function v2 ($ myArray = null ){
// The efficiency is slightly improved
$ Max = sizeof ($ myArray );
For ($ I = 0; $ I <$ max; $ I ++)
{
Echo' ';
}
}

Function v3 ($ myArray = null ){
// Optimal Efficiency
Echo" ";
}
?>

The output result of the program is as follows:

V1 ran 100 times where average exec time 0.18400 MS
V2 ran 100 times where average exec time 0.15500 MS
V3 ran 100 times where average exec time 0.09100 MS

As you can see, the function execution time decreases and the efficiency increases.
Function v1 has a very obvious error. the sizeof () function must be called to calculate each cycle time. Function v2 saves the number of elements in the $ myArray array to the $ max variable outside the loop, avoiding the need to calculate the number of elements in the array in each loop, so the efficiency is improved. Function v3 is the most efficient and uses ready-made functions to avoid loops.
This example only gives you a perceptual understanding of what is relatively efficient code. In actual development, I believe many people will write a lot of inefficient code. I'm afraid it will take time to refine the code:-) but this is another topic. let's skip it.
Database applications are basically used by every PHP program. in actual development, I found that the most influential part of the system efficiency is the database. Database optimization and data query statement optimization are not discussed in detail. You can refer to these two articles:
Http://www.phpe.net/articles/340.shtml
Http://www.phpe.net/articles/323.shtml
And this discussion:
Http://club.phpe.net/index.php? S... mp; t = 4783 & st = 0 (I have summarized some of the previous posts), mainly for MySQL.

◆ Compressed output gzip

Using the mod_gzip module in Apache, we can use the gzip compression algorithm to compress the webpage content published by the Apache server and then transmit it to the browser of the client. If it is a plain text content, the effect is very obvious, it can be compressed to the original 30%-40%, so that the user's browsing speed is greatly accelerated.
Gzip requires support from client browsers. most browsers currently support gzip, such as IE, Netscape, and Mozilla. Therefore, this method is worth a try. We can use the predefined variable $ _ SERVER ['http _ ACCEPT_ENCODING '] in PHP to determine whether the client browser supports gzip.

Gzip1.php


If (ereg ('gzip ', $ _ SERVER ['http _ ACCEPT_ENCODING']) {
// Browser support
} Else {
// The browser does not support output of other content
}
?>

Next, we will expand the above PHP program, use ob_start (ob_gzhandler) to compress the webpage content, store the content in the buffer, and send it to a browser that supports gzip. the browser will automatically decompress the compressed content, display.

Gzip2.php

Define ('Max ', 100 );

If (ereg ('gzip ', $ _ SERVER ['http _ ACCEPT_ENCODING'])
{
// The browser supports gzip to compress the content and buffer the output.
Ob_start ("ob_gzhandler ";
$ Output = '';

For ($ I = 0; $ I <= MAX; $ I ++)
{
$ Output. = "This is line $ I
";
}
Echo "the browser supports gzip compressed output
";
Echo $ output;
}
Else
{
// The browser does not support direct output.
For ($ I = 0; $ I <= MAX; $ I ++)
{
$ Output. = "This is line $ I
";
}

Echo "the browser does not support gzip compressed output
";
Echo $ output;
}
?>


The HTTP header information of a web page generated by using gzip compression is more like this than that of a general web page:

Content-Encoding: gzip
Content-Length: 270

For more details, see the mod_gzip project homepage:
Http://sourceforge.net/projects/mod-gzip/

Similarly, we can also use mod_deflate to lower the compression ratio than mod_gzip. Calling the zip function consumes server memory, so use it with caution, depending on your needs.

◆ Content cache output PEAR cache

Next we will start to explore more common cache Technologies, which is also the key part of this article. First, we use the cache package in PEAR. PEAR can cache content in files, databases, or memory. We use files as an example.
Below is a PHP applet that does not use the cache:

Pear_content_cache1.php

Echo "this is the content.

";
Echo "the current time is". date ('M-d-y h: I: s A', time ())."
";
?>

The above program is very simple. Now we add cache for it.

Pear_content_cache2.php

Require_once 'cache/Output. php ';

// Set the cache directory, which must be writable.
$ CacheDir = './pear_cache ';
$ Cache = new Cache_Output ('file', array ('cache _ dir' => $ cacheDir ));

// If the nocache variable is empty, use the content in the cache.
// If you want to obtain the latest content, assign the value to the nocache variable.
If (empty ($ _ REQUEST ['nocache'])
{
// Create a unique cache ID
// Request + Cookie information
$ Cache_id = $ cache-> generateID (array ('URL' = >$ _ REQUEST, 'post' = >$ _ post, 'Cookies '= >$ HTTP_COOKIE_VARS ));
}
Else
{
// If you want to obtain the latest content, the ID is blank.
$ Cache_id = null;
}


// Check whether the cache content corresponding to the cache ID is available
If ($ content = $ cache-> start ($ cache_id ))
{
// Cache already exists, output directly, and end the script
Echo $ content;
Exit ();
}

// This content does not exist in the cache. new content is generated and written to the cache.
Echo "this is the content.

";
Echo "the current time is". date ('M-d-y h: I: s A', time ())."
";
// Write the content to the cache
Echo $ cache-> end ();
?>

Refresh the two files respectively. you will find that the time in the "current time is" line in pear_content_cache1.php changes with the refresh, while the time in pear_content_cache2.php remains unchanged. This is because pear_content_cache2.php uses the cache to store the content requested by the user into a static file. When the user requests again, it directly outputs the content from the file, instead of using the program to dynamically generate the content.
For pear_content_cache2.php, if you want to read the latest information, rather than cache the old information. You can use http ://... /Pear_content_cache2.php? Nocache = 1. this will disable the cache function. Refresh the page and you will find that the time changes accordingly.
To sum up the usage of the PEAR content cache class:
1. note the correct path when the PEAR package is included.
2. cache class included in Output. php
Require_once 'cache/Output. php ';
3. set cache Directory
$ CacheDir = './pear_cache ';
Make sure the directory is writable. The Cache data will be written into the subdirectory of this directory.
4. create an output cache object
$ Cache = new Cache_Output ('file', array ('cache _ dir' => $ cacheDir ));
The first parameter indicates that we use the file-based cache, and the second parameter is an array associated with the cache directory.
5. generate a unique cache ID
$ Cache_id = $ cache-> generateID (array ('URL' = >$ _ REQUEST, 'post' = >$ _ post, 'Cookies '= >$ HTTP_COOKIE_VARS ));
Here, the generateID () method of the $ cache object uniquely identifies this request by providing an information array (URL, http post data, and HTTP cookie), which is differentiated from other requests.
6. add a logical judgment statement to check whether the cache data corresponding to cacheID already exists. if so, obtain the data and end the script.
If ($ content = $ cache-> start ($ cache_id ))
{Echo $ content;
Exit ();
}
7. Place the code of the generated content after the preceding logic statement and end the use of the cache object.
Echo $ cache-> end ();

◆ Function cache output PEAR cache

In addition to caching the output content, PEAR can also cache the call results of a function. This is a very interesting feature. if your program needs to use a function frequently and the call results are the same, I suggest you try it, especially when this function runs slowly.

Below we implement a buffer call to a function slowFunction () that is executed very slowly.

Require_once 'cache/Function. php ';


$ CacheDir = './pear_cache /';
$ Cache = new Cache_Function ('file', array ('cache _ dir' => $ cacheDir ));
$ Arr = array ('apple', 'Lil', 'watermelon ');
$ Cache-> call ('slowfunction', $ arr );
Echo'
';

$ Arr = array ('apple', 'Lil', 'watermelon ');
SlowFunction ($ arr );

Function slowFunction ($ arr = null)
{
Echo "a function that is very slow to execute
";
Echo "current time is". date ('M-d-y h: I: s A', time ()).'
';
Foreach ($ arr as $ fruit)
{
Echo "I ate a $ fruit
";
}
}
?>

The execution result of the sample script is as follows:
A function that is very slow to execute
Current time is Jul-28-2004 17:15:57
I ate an apple
I ate a pear.
I ate a watermelon.

A function that is very slow to execute
Current time is Jul-28-2004 17:17:55
I ate an apple
I ate a pear.
I ate a watermelon.
In the code, the Cache/Function. php class is used to execute the Function buffer Function. $ Cache variable is a Cache_Function object. it is saved to the $ cacheDir Directory using file-based function caching. To cache a function call, use the call () method of the Cache_Function object $ cache as follows: $ cache-> call ('slowfunction', $ arr );
Here, the slowFunction () function is called and the parameter is an array $ arr, which is cached in a file under the $ cacheDir directory. Any subsequent call to this function will return the execution result of this function by $ cache-> call.
Function caching is similar to content caching. For more information, see the PEAR manual.

All of the above uses the optimization code method to speed up the program. next we should take a look at another field of PHP acceleration-cache tool software. This type of software is accelerated by optimizing the PHP runtime environment without changing any code. We can refer to them as "execution code optimization/cache tools". you can refer to them for lower-layer optimization/caching.

The following lists the commonly used tools. use your own server environment to test the effect:
(1) APC Alternative PHP Cache
Http://apc.communityconnect.com/
APC runs on Linux and FreeBSD. you need to compile and install it yourself. According to their developers, the script speed can be increased by 50%-400% in their testing environment. APC is an open-source project that has been added to the PECL library of PHP. it is worth a try.
(2) Turck MMCache
Http://turck-mmcache.sourceforge.net/
Turck MMCache seems to be the most popular among such software. it is open-source and completely free of charge. It pre-compiles and caches PHP code and optimizes the PHP runtime environment. According to the official documentation, MMCache can significantly reduce the server load and increase the script execution speed by 1-10 times.
MMCache is compatible with another well-known acceleration software Zend Optimizer, but note that MMCache must be installed first (set in php. ini ). In addition to accelerating PHP programs, MMCache can also encrypt PHP code.
Turck MMCache supports both Linux and Win32 platforms.
(3) PHPA the PHP Accelerator
Http://www.php-accelerator/
PHPA is another popular PHP acceleration software. On its official website, PHP scripts using PHPA, APC, and Zend Cache are used for test comparison, which is slightly better than APC and slightly inferior to Zend Cache.
PHPA supports Linux, FreeBSD, OpenBSD, BSDi, and Solaris systems.
(4) Zend Performance Suite
Http://www.zend.com/
Zend Performance Suite is a well-established PHP acceleration/optimization software based on Zend, the most well-known PHP Company. Version 4.0 has been released, which can provide program acceleration, content caching, file compression, and download services for PHP applications. it has powerful functions and won several PHP magazine recommendation awards-but I have to mention it, it is also expensive. The current price is USD 1875.
The above acceleration software is expected to be tested by the reader based on the server environment and select the most suitable one, because I have no way to provide a universally applicable test standard to determine which solution is the most effective. In summary, I personally think Turck MMCache is a recommendable option. it is free of charge and has excellent functions.

(Iv) summary

The above describes PHP acceleration technologies in a comprehensive and meticulous manner from multiple perspectives, including testing and acceleration technologies (compression and caching). code and examples are provided. I hope this article will help readers fully understand PHP program acceleration and select an appropriate acceleration solution in practical applications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.