Home php教程 php手册 代码从业者的一次php应用优化实践

代码从业者的一次php应用优化实践

Jun 21, 2016 am 08:53 AM
cache cpu framework memcached

   系统跑得时间长了,总会出现这样那样的问题和瓶颈,有了问题不可怕,我们有“打虎”的家伙事儿--无非就是定位问题->分析问题->提出解决方案->实践->结果反馈->总结再优化。

  之前做过的一次优化实践,最近翻出来看看,有些通用的优化手段还是可以复用的。系统跑得时间长了,总会出现这样那样的问题和瓶颈,有了问题不可怕,我们有“打虎”的家伙事儿--无非就是定位问题->分析问题->提出解决方案->实践->结果反馈->总结再优化。

  问题描述:系统采用 PHP5 + Zend framework 开发,在数据规模和访问量增加后(千万级),出现了后台apache服务器负载过高的现象,在访问高峰时段(比如每天下班到晚上10点这一段时间,特别是周五),机器CPU负载会飙升到170多,CPU负载过高造成处理请求也相应的变慢,所以亟需解决这个问题。

  问题分析:通过连续几天的观察和分析,当CPU使用率达到100%时,其中系统CPU使用率占据了很大的比例,用户CPU使用率倒不是很高,另外前端 haproxy 和 squid cache的cpu负载很低,memcached和squid的hit ratio一般都能达到60%左右。

  分析backend的access-log,发现相当大一部分请求的User-Agent是搜索爬虫;

  同时,在 apache 上配置了xdebug,在空闲时段对主要的页面的测量了一组性能数据,通过使用kcachegrind对测得的数据进行分析(如何配置xdebug,可以用soso搜一下),发现:

  性能数据不够稳定,同样的请求之间测试数据会相差比较大

  慢的点比较分散

  memcached的访问大部分的情况都比较慢(100ms以上)

  解决方案通过上述初步的分析,对现有的程序逐步作了一系列调整。

  首先考虑到的是是否可以想办法增加前端squid cache的Hit ratio,从而减少穿透squid到达后端apache的请求数。

  考虑到相当一部分请求来源于Crawler,而之前squid cache只会对设置了language cookie的请求作cache,而来自Crawler的请求都没有cookie信息。于是想到把来自Crawler的请求都默认为language为zh_CN的,然后修改haproxy的配置,把User-Agent为常见的Crawler的请求都转交给squid cache.

  修改php代码,把一些页面的缓存时间设置得更长一些

  经过如上两个步骤,到达apache的请求确实减少了一些,但是这个对cpu负载过高的问题帮助很少,于是另寻它法。

  其次,根据使用 xdebug profiling的结果来看,和memcached的交互耗时比较长,于是想是否可以想办法让memcached能更快地响应请求,从而使得每一次请求能更快完成,从而使并发降低。

  通过代码分析,发现线上memcached使用的是poll(),而memcached的连接数在繁忙的时候保持在1000左右,memcached的CPU使用率在 30% 左右。很显然,poll()方式在处理如此多的并发连接时是很低效的。于是重新编译memcached,使其使用epoll()的方式来处理请求,替换为epoll之后,memcached的cpu usage从 30%左右降低到 3% 左右,10倍之多!

  另外,memcached的hit ratio不是特别高,而且被换出的item数也比较高,于是想到对cache的内容作partition.原本打算做 manually partition,后来发现php的最新的memcache扩展就能支持根据cache的key自动作partition,而且能在不修改程序代码(需要修改配置文件:-))的情况下增加新的memcached实例。于是升级每一个apache的php memcache扩展,然后再配置文件中增加了一台新的memcached。到此完成memcached的内容partition。修改之后的效果比较显著,页面的载入时间比修改前缩短了很多。

  经过这两步的调整,memcached的效率比以前高了,但是apache的负载仍然居高不下,没辙,再想其它办法!

  进一步深入分析前面说到主要系统CPU占用很高,要找原因只能深入内核了:) 从现在开始了我们的strace之旅。套用一句Nike的广告词:Just strace it!

  在高峰时段对 httpd 进程进行了strace,方法不外乎如下这些

  strace -p PID -c 得出 summary

  strace -p PID -o output.log 写入文件,慢慢研究

  strace -p PID -e trace=file 只看 filesystem 操作相关的 syscalls

  strace -p PID -elstat64,stat64,open,getcwd 只跟踪这些 syscalls

  …

  从上述strace分析得到如下结论:

  lstat64,stat64,open等 syscalls实在是多啊

  上述 syscalls 占用时间确实不少! 60%以上的时间都被它们抢了, orz

  绝大多数 syscall 是失败的,真是屡败屡战啊

  有了上述数据,我们就找到了问题的方向了,那就是找这些毫无意义的系统调用是怎么来的。

  经过分析,这些是php要加载某一个类时,会去 include_path 中定义的一系列目录中搜寻该类对应的文件,挨个目录这么试过去,直到找到为止。嗯,这种方式显然是比较低效的,有没有更好的方式来完成这个事情呢?答案是肯定的,有!而且还有不止一种方法!

  调用require_once()时,参数写绝对路径(开始Guys write Zend Framework就不懂这个道理;后来才有更新))

  使用 __autoload()对class进行 lazy loading,也就是说真正需要的时候才去加载,而不是不管三七二十一把可能用到的类文件都require_once了。

  问题是找到了,但是要解决这个问题还面临着另一个问题。开发中代码都注意用绝对路径了,唯一可以改进的地方是改为 lazy loading,但是 Zend Framework中大量的require_once采用相对路径,这个就是导致问题——这里我说的问题是本文我们谈论的CPU负载过高的问题——的根本原因。

  OK,既然问题找到了,动手解决。写个脚本自动生成 Class -> File Path 对应关系,生成代码中所有类和Zend Framework中所有类的对应关系文件。把代码中和Zend Framework库中所有的 require_once 都注释掉。然后进行详细的测试,然后上线。结果令人吃惊,负载降到了 3 以内!!问题解决。

  总结:

  写代码的人都知道,可能出问题的地方总会出问题,任何问题都会有个原因(哪怕暂时没有找到),从根上解决才是王道,解决什么问题不重要,希望大家能学习这个解决的思路,善于利用工具。ok,这个case就这样了。




Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
What should the CPU utilization be when gaming? What should the CPU utilization be when gaming? Feb 19, 2024 am 11:21 AM

It's common for games to slow down your computer because they consume a lot of resources. It's crucial to understand your CPU usage when gaming so you can avoid overloading it. Therefore, keeping track of appropriate CPU usage is key to keeping your gaming experience smooth. In this article, we'll look at the appropriate CPU usage you should achieve while your game is running. CPU utilization during gaming CPU utilization is an important indicator of processor workload and depends on the performance specifications of the CPU. More powerful CPUs generally have higher usage. A CPU with more cores and threads can improve the overall performance of your system. Multi-threading support helps unleash the full potential of your CPU. In games, CPU usage depends on processor utilization, which can affect the game

How to set CPU performance to full in Win11 How to set CPU performance to full in Win11 Feb 19, 2024 pm 07:42 PM

Many users find that the computer is not running smoothly enough when using the Win11 system. They want to improve CPU performance, but they don't know how to do it. The following will introduce in detail how to set the CPU performance to the highest level in Win11 system to make your computer more efficient. Setting method: 1. Right-click "This PC" on the desktop and select "Properties" in the option list. 2. After entering the new interface, click "Advanced System Settings" in "Related Links". 3. In the window that opens, click the "Advanced" tab at the top, then click the & at the bottom of "Performance"

How to increase the clock frequency of your computer's CPU How to increase the clock frequency of your computer's CPU Feb 20, 2024 am 09:54 AM

How to Overclock Computer CPUs With the continuous advancement of technology, people's demand for computer performance is also getting higher and higher. An effective way to improve computer performance is to increase the CPU's operating frequency through overclocking. Overclocking allows the CPU to process data faster, providing higher computing power. So, how to overclock a computer CPU? The following will introduce you to the basic principles and specific operation methods of overclocking. First, let's understand how overclocking works. The operating frequency of the CPU is determined by the crystal oscillator on the motherboard

The difference between boxed and bulk cpu The difference between boxed and bulk cpu Jan 23, 2024 am 09:46 AM

The differences between boxed and bulk CPUs: 1. Quality; 2. Warranty period; 3. Fan; 4. Price; 5. Packaging; 6. Sales channels. Detailed introduction: 1. Quality, whether it is boxed or bulk, there is no difference in the quality of the CPU itself. They are all manufactured by the same manufacturer and undergo the same quality testing and quality control process; 2. Warranty period, boxed CPU A longer warranty period is usually provided, usually three years, while bulk CPUs usually only have a one-year warranty, this is because boxed CPUs are usually sold by official or authorized dealers, etc.

How to undervolt and overclock your CPU using Intel XTU How to undervolt and overclock your CPU using Intel XTU Feb 19, 2024 am 11:06 AM

Intel XTU is a powerful application that allows you to easily manage your computer's performance. You can fix overheating issues by adjusting the CPU voltage, or boost performance by overclocking. In this article, we'll look at how you can take advantage of Intel XTU to optimize your computer's performance, whether that's adjusting voltage or overclocking. What effect do undervolting and overclocking have on the CPU? Before we move on to learning how to undervolt and overclock a CPU, we first have to understand what they are. Undervolting refers to gradually reducing the voltage required by the CPU. This process helps reduce heat emissions, as high voltage results in higher temperatures. By reducing the voltage supply to the CPU, the temperature can be effectively reduced. If your laptop starts to slow down after getting hot, you should solve the problem promptly.

144-core, 3D-stacked SRAM: Fujitsu details next-generation data center processor MONAKA 144-core, 3D-stacked SRAM: Fujitsu details next-generation data center processor MONAKA Jul 29, 2024 am 11:40 AM

According to news from this website on July 28, foreign media TechRader reported that Fujitsu introduced in detail the FUJITSU-MONAKA (hereinafter referred to as MONAKA) processor planned to be shipped in 2027. MONAKACPU is based on the "cloud native 3D many-core" architecture and adopts the Arm instruction set. It is oriented to the data center, edge and telecommunications fields. It is suitable for AI computing and can realize mainframe-level RAS1. Fujitsu said that MONAKA will achieve a leap in energy efficiency and performance: thanks to technologies such as ultra-low voltage (ULV) technology, the CPU can achieve 2 times the energy efficiency of competing products in 2027, and cooling does not require water cooling; in addition, the application performance of the processor It can also reach twice as much as your opponent. In terms of instructions, MONAKA is equipped with vector

The operation process of WIN10 service host occupying too much CPU The operation process of WIN10 service host occupying too much CPU Mar 27, 2024 pm 02:41 PM

1. First, we right-click the blank space of the taskbar and select the [Task Manager] option, or right-click the start logo, and then select the [Task Manager] option. 2. In the opened Task Manager interface, we click the [Services] tab on the far right. 3. In the opened [Service] tab, click the [Open Service] option below. 4. In the [Services] window that opens, right-click the [InternetConnectionSharing(ICS)] service, and then select the [Properties] option. 5. In the properties window that opens, change [Open with] to [Disabled], click [Apply] and then click [OK]. 6. Click the start logo, then click the shutdown button, select [Restart], and complete the computer restart.

Leak reveals key specs of Intel Arrow Lake-U, -H, -HX and -S Leak reveals key specs of Intel Arrow Lake-U, -H, -HX and -S Jun 15, 2024 pm 09:49 PM

IntelArrowLakeisexpectedtobebasedonthesameprocessorarchitectureasLunarLake,meaningthatIntel'sbrandnewLionCoveperformancecoreswillbecombinedwiththeeconomicalSkymontefficiencycores.WhileLunarLakeisonlyavailableasava

See all articles