PHP应用程序的性能优化
程序|性能|优化
使用PHP编程的最大好处是学习这种编程语言非常容易以及其丰富的库。即使对需要使用的函数不是十分了解,我们也能够猜测出如何完成一个特定的任务。
尽管PHP非常简单易学,但我们仍然需要花费一点时间来学习PHP的一些编程技巧,尤其是与性能和内存占用相关的技巧。在PHP中,有许多小技巧能够使我们减少内存的占用,并提高应用程序的性能。在本篇文章中,我们将对PHP应用程序的分析、如何改变脚本代码以及比较优化前后的各种参数值进行简要的介绍。
通过在程序中设置计时的程序,并反复执行这些代码,我们可以获得有关程序执行速度的一组数据,这些数据可以可以用来发现程序中的瓶颈,以及如何进行优化,提高应用程序的性能。
也许读者曾经听说过PEAR库吧。我们将使用PEAR库创建在分析时需要使用的例子,这也是对现有的代码进行分析的最简单的方法,它使我们无需使用商用产品就能对代码进行分析。
我们要使用的库的名字是PEAR::Benchmark,它对于对代码进行分析和性能测试非常有用。这个库提供一个名字为Benchmark_Timer()的类,能够记录一个函数调用和下一个函数调用之间的时间。在对代码的性能进行测试时,我们可以得到一个详细的脚本执行结果,它非常简单,如下所示:
include_once("Benchmark/Timer.php");
$bench = new Benchmark_Timer; $bench->start();
$bench->setMarker('Start of the script'); 现在处于睡眠状态几分钟
sleep(5); $bench->stop(); // 从计时器中获得分析信息
print_r($bench->getProfiling());
?>
上面代码执行后的输出如下所示:
Array
(
[0] => Array
(
[name] => Start
[time] => 1013214253.05751200
[diff] => -
[total] => 0
)
[1] => Array
(
[name] => Start of the script
[time] => 1013214253.05761100
[diff] => 9.8943710327148E-05
[total] => 9.8943710327148E-05
)
[2] => Array
(
[name] => Stop
[time] => 1013214258.04920700
[diff] => 4.9915959835052
[total] => 4.9916949272156
)
)
上面的数字似乎是一组杂乱无章的数字,但如果程序的规模更大,这些数字就十分地有用了。
也许广大读者也能猜测到,数组的第一个表目是实际调用Benchmark_Timer()类的方法,例如
$bench->start()、$bench->setMarker()和$bench->stop(),与这些表目有关的数字是相当简单的,现在我们来仔细地研究这些数字:
[0] => Array
(
[name] => Start
[time] => 1013214253.05751200
[diff] => -
[total] => 0
)
time表目指的是何时对Benchmark_Timer()的start()方法调用的UNIX的timestamp,diff表目表示这次调用和上次调用之间的时间间隔,由于这里没有上一次,因此显示出了一个破折号,total表目指的是自测试开始到这一特定的调用之前代码运行的总的时间。下面我们来看看下一个数组的输出:
[1] => Array
(
[name] => Start of the script
[time] => 1013214253.05761100
[diff] => 9.8943710327148E-05
[total] => 9.8943710327148E-05
)
从上面的数字我们可以看出,在调用$bench->start()之后,程序运行了9.8943710327148E-05秒(也就是
0.0000989秒)后开始调用$bench->setMarker(....)。
一次真实的性能测试经历
尽管上面的例子不错,但在对于决定如何优化你的站点代码设计方面,它真的不能算是一个好例子。下面我将用我自己作为网站技术人员的一段亲身经历来说明如何解决性能方面存在的问题。
我并不大理解网站使用的代码,因为它是根据特殊的需求,历经多年开发而成的━━其中的一个模块包括网站转换代码,另一个模块记录网站的使用情况,其他的模块也各有各的作用。我和网站的主要开发者都意识到网站的代码需要优化,但又不清楚问题出在哪儿。
为了尽快地完成任务,我开始研究网站的主要脚本代码,并在全部脚本代码以及其包含文件中添加了一些$bench->setMarker()命令,然后分析$bench->getProfiling()的输出,并对得到的结果大吃一惊,原来问题出在一个与获得特定语言名字(例如en代表english)的转换代码的函数调用中,该函数在每个页面上都会被使用数百次。每次调用该函数时,脚本代码都会对一个MySQL数据库进行查询,从一个数据库表中获得真正的语言名字。
于是我们这一类的信息创建了一个缓冲系统。经过短短2天时间的工作,我们使系统的性能得到了很大的提高,第一周内页面的浏览量也因此而增加了40%。当然了,这只是一个有关分析代码能够提高互联网应用或互联网网站性能的例子。
性能测试函数调用
在分析一个脚本或网页(以及其包含文件)时,尽管Benchmark_Timer()特别有用,但它并不科学,因为要获得分析的数据我们必须多次加载脚本,而且它也不是针对某个类或函数调用的。
PEAR::Benchmark库中的另一个被称作Benchmark_Iterator的类能够很好地解决这一个问题,它能够针对特定的函数或类的方法,显示其分析信息。它的用途是能够能够从测试中获得一致的结果,因为我们知道,如果运行一段脚本一次,其运行时间为10秒,并不意味着它每次的运行时间总是10秒。
In any case, let's see some examples:
// 连接数据库的代码
include_once("DB.php");
$dsn = array(
'phptype' => 'mysql',
'hostspec' => 'localhost',
'database' => 'database_name',
'username' => 'user_name',
'password' => 'password'
);
$dbh = DB::connect($dsn); function getCreatedDate($id)
{
global $dbh; >$stmt = "SELECT created_date FROM users WHERE id=$id";
// 在这里使用PEAR::DB
$created_date = $dbh->getOne($stmt);
if ((PEAR::isError($created_date)) ||
(empty($created_date))) {
return false;
} else {
return $created_date;
}
}include_once 'Benchmark/Iterate.php';
$bench = new Benchmark_Iterate; // 运行getDate函数10次
$bench->run(10, 'getCreatedDate', 1);// 打印分析信息
print_r($bench->get());
?>
运行上面的代码能够产生与下面相似的结果:
Array
(
[1] => 0.055413007736206
[2] => 0.0012860298156738
[3] => 0.0010279417037964
[4] => 0.00093603134155273
[5] => 0.00094103813171387
[6] => 0.00092899799346924
[7] => 0.0010659694671631
[8] => 0.00096404552459717
[9] => 0.0010690689086914
[10] => 0.00093603134155273
[mean] => 0.0064568161964417
[iterations] => 10
)
上面的这些数字很好理解,mean条目表示getCreatedDate()函数10次运行的平均时间。在进行实际测试时,应该至少运行1000次,但这个例子得出的结果已经足够说明问题了。
结束语
希望广大读者能够通过本篇文章掌握如何迅速地对PHP代码进行分析的基本方法。在这里我还还要提醒广大读者的是,对代码进行分析不是一件简单的事儿,因为我们必须掌握大量的有关该种语言的特性。在代码中添加计时用的代码有助于找出运行速度缓慢的函数,利用多次重复的方法使我们能够发现对代码进行正确优化的方法。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Solution to docker start failure: 1. Check the running status, and then release the occupied memory through the "echo 3 > /proc/sys/vm/drop_caches" command; 2. Use "$netstat -nltp|grep .. ." command to check whether the port has been occupied. If it is found to be occupied after going online, change it to an available port and restart.

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

Solution to node start error: 1. Execute "node xx.js" directly in the terminal; 2. Add start startup item "scripts": {"test": "echo \"Error: no test specified\" && exit 1 ","start":"node service.js"}"; 3. Re-execute "npm start".

Watch4pro and gt each have different features and applicable scenarios. If you focus on comprehensive functions, high performance and stylish appearance, and are willing to bear a higher price, then Watch 4 Pro may be more suitable. If you don’t have high functional requirements and pay more attention to battery life and reasonable price, then the GT series may be more suitable. The final choice should be decided based on personal needs, budget and preferences. It is recommended to carefully consider your own needs before purchasing and refer to the reviews and comparisons of various products to make a more informed choice.

How to Optimize iPad Battery Life with iPadOS 17.4 Extending battery life is key to the mobile device experience, and the iPad is a good example. If you feel like your iPad's battery is draining too quickly, don't worry, there are a number of tricks and tweaks in iPadOS 17.4 that can significantly extend the run time of your device. The goal of this in-depth guide is not just to provide information, but to change the way you use your iPad, enhance your overall battery management, and ensure you can rely on your device for longer without having to charge it. By adopting the practices outlined here, you take a step toward more efficient and mindful use of technology that is tailored to your individual needs and usage patterns. Identify major energy consumers
