Exploration of PHP Program Acceleration

Source: Internet
Author: User
Tags apc benchmark ereg http cookie pear php source code time 0 server memory

Introduction: This is a detailed page for PHP Program Acceleration exploration. It introduces PHP, related knowledge, skills, experience, and some PHP source code.

Class = 'pingjiaf' frameborder = '0' src = 'HTTP: // biancheng.dnbc?info/pingjia.php? Id = 324442 'rolling = 'no'>

-(1) 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

<? 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 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

<? 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

<? 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 '<br> ';
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 '<! -- '. $ Myarray [$ I].' --> ';
}
}

Function V2 ($ myarray = NULL ){
// The efficiency is slightly improved
$ Max = sizeof ($ myarray );
For ($ I = 0; $ I <$ Max; $ I ++)
{
Echo '<! -- '. $ Myarray [$ I].' --> ';
}
}

Function V3 ($ myarray = NULL ){
// Optimal efficiency
Echo "<! -- ", Implode (" --> <! -- ", $ Myarray)," --> ";
}
?>

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

<? 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

<? 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

<? PHP
Echo "this is the content. <P> ";
Echo "the current time is". Date ('m-D-y h: I: s A', time (). "<br> ";
?>

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

Pear_content_cache2.php

<? 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. <P> ";
Echo "the current time is". Date ('m-D-y h: I: s A', time (). "<br> ";
// 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.

<? PHP
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 '<br> ';

$ Arr = array ('apple', 'lil', 'watermelon ');
Slowfunction ($ ARR );

Function slowfunction ($ arr = NULL)
{
Echo "a function that is very slow to execute <br> ";
Echo "current time is". Date ('m-D-y h: I: s A', time (). '<br> ';
Foreach ($ arr as $ fruit)
{
Echo "I ate a $ fruit <br> ";
}
}
?>

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.

More articles on "php program accelerated exploration"

Love J2EE follow Java Michael Jackson video station JSON online tools

Http://biancheng.dnbcw.info/php/324442.html pageno: 14

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.