设为首页 收藏本站
查看: 522|回复: 0

[经验分享] Debugging and Profiling PHP with Xdebug

[复制链接]

尚未签到

发表于 2017-4-1 08:01:50 | 显示全部楼层 |阅读模式
  http://www.sitepoint.com/debugging-and-profiling-php-with-xdebug/
  PHP is the most popular language for web development, but a common criticism against it used to be that it lacked a suitable debugger. Developers using languages like Java and C# enjoy a powerful suite of debugging tools, often integrated directly with their IDEs. But the disconnected nature of web servers and PHP IDEs prevented us from having many of the same tools available. We manually added debug statements in our code… until Xdebug filled the void.
  Xdebug is a free and open source project by Derick Rethans and is probably one of the most useful PHP extensions. It provides more than just basic debugging support, but also stack traces, profiling, code coverage, and so on. In this article you’ll see how to install and configure Xdebug, how to debug your PHP application from Netbeans, and how to read a profiling report in KCachegrind.

Installing and Configure Xdebug
  If you are using XAMPP or MAMP, Xdebug comes preinstalled; you just need to enable it in your php.ini. If you are using a package based installation on a platform such as Ubuntu, you can install it through your package manager with a command like apt-get install php5-xdebug.
  The entries for Xdebug in my php.ini look like this:

[xdebug]
zend_extension="/Applications/MAMP/bin/php5.2/lib/php/extensions/no-debug-non-zts-20060613/xdebug.so"
xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000
  zend_extension specifies the path to the Xdebug module. The xdebug.remote_enable value toggles whether the extension is active or not. xdebug.remote_host is the name or the IP address of your system (here I’ve specified localhost because I’m working all on the same machine, but the value can be an IP Address or a DNS hostname if you need to specify something different for your setup). xdebug.remote_port is the port on which the client listens for a connection from Xdebug (9000 is the default value).
  When you use Xdebug, it’s important to make sure you are not using any other Zend extensions since they may conflict with Xdebug.
  There are other installation options as well. The Xdebug website provides a simple wizard to guide you through installation. You can take the output of phpinfo() or php –i and paste it in the text box and have the wizard analyze your server’s configuration and instruct you on how to compile Xdebug for your machine.

Debugging
  More often than not it’s tempting to use the var_dump() and exit/die() combination for debugging. But the problem with this approach is that you have to modify the code for debugging; you must remember every place you added output statements and remove them after debugging is finished. Xdebug overcomes this by letting you pause your application’s execution where ever you want. Then you can inspect the variables’ values in that scope to get better insight into what PHP is doing.
  You can easily configure Netbeans to act as an Xdebug client. Open the options window (Tools > Options) and go to the debugging tab for the PHP section. Enter the debugging port given in php.ini and a Session ID which you’ll need to pass with the requests you want to debug. Now you’ll be able to run the debugger by clicking Debug in the tools tab.
DSC0000.png

  With your source file open, press the Debug button in the toolbar to start debugging. It will open up the application in a browser, and PHP’s execution will pause at the first line of the file if you have enabled the “Stop at first line” option in the Options window. Otherwise, it will run until it encounters the first breakpoint. From there you can continue to the next break point using the continue button.
  Notice in the brower’s URL bar the XDEBUG_SESSION_START parameter. To trigger the debugger you must pass XDEBUG_SESSION_START as a request parameter (GET/POST) or XDEBUG_SESSION as a cookie parameter.
  There are some other useful actions in the debugging toolbar. They are:


  • Step over – Step over the currently executing line
  • Step into – Step into the function (for non-built-in functions)
  • Step out – Step out of the current function
  You can add breakpoints by clicking the line number in the editor’s margin and then pause execution on them. They can be removed by clicking on them again. Alternatively, go to Window > Debugging > Breakpoints which will list all breakpoints in your program and you can select/deselect only those you needed.
  While running, the state of the variables in the current scope are shown in the variables window. It will show the values of local variables and super global variables like $_COOKIE, $_GET, $_POST and $_SERVER. You can watch their values change as you step through through the statements.
DSC0001.png


Profiling
  Profiling is the first step when optimizing any application. Profiling tools record important details like the time it takes for statements and functions to execute, the number of times they are called, and so on. The output can be analyzed to understand where the bottlenecks are.
  Xdebug can also be used as a profiling tool for PHP. To start profiling your applications, add the following settings to php.ini:

xdebug.profiler_enable = 1
xdebug.profiler_output_name = xdebug.out.%t
xdebug.profiler_output_dir = /tmp
xdebug.profiler_enable_trigger = 1
  Profiling is disabled by default in Xdebug, so xdebug.profiler_enable is used to enable it. xdebug.profiler_output_name is the filename of the profiler log (the %t specifier appends a timestamp to the filename; see the documentation for a full list of specifiers). Xdebug stores the profiling output in the directory specified by xdebug.profiler_output_dir. You can can change this to a location of your choice, but remember it must have write permissions for the user account under which the PHP script is run.
  Profiling degrades performance since the PHP engine need to look af each function call and log its details, so you don’t want to run it all the time. xdebug.profiler_enable_trigger instructs Xdebug to perform profiling only when XDEBUG_PROFILE is passed as a GET or POST parameter.
  The log file created by Xdebug can be small or large depending on what the application is doing. Also, it’s not really reader friendly. You’ll want to use programs like KCachegrind or Webgrind to view them. KCachegrind is a profile data visualization tool for KDE, which needs a Unix environment to run, whereas Webgrind is a web-based tool.
  Opening the profiling long file in KCachegrind will show the cost of each function call starting at main(). Here is the KCachegrind visualization of profiling output of a function to find a factorial:
DSC0002.png

  The left side panel (Function Profile) shows the time taken by each function in their execution order. The top right panel graphically displays the same information with the size corresponding to the cost of the function. The call graph represents the relationship between functions in the application. In this example there are only two functions, main() and fact(). fact() is a recursive function, which is indicated using a cycle in the graph.
  While optimizing your code, you should look for the areas with highest total cost. More often than not, I/O operations will have the highest cost. Remember to reduce them as much as possible. Lazy load files wherever that makes sense.
  Suppose you have a class named Orders which will give you a list of all orders and their details from your web store.


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31


<?php

class Orders


{

    protected $db;


 

    public function __construct(PDO $db) {


        $this->db = $db;


    }


     

    public function getAll() {


        $orders = array();


        $query = "SELECT * FROM orders";


        $result = $this->db->query($query);


        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {


            $row['details'] =


                $this->getDetails($row['orderId']);


            $orders[] = $row;


        }


 

        return $orders;


    }


     

    public function getDetails($orderId){


        $details = array();


        $result = $this->db->query("SELECT * FROM orderdetails WHERE orderId = " . $orderId);


        while ($row = $result->fetch(PDO::FETCH_ASSOC)) {


            $details[] = $row;


        }


        return $details;


    }


}







  This class has two methods: getAll() and getDetails(). When you call the getAll() method, it will get all of the records from the orders table and loop through them to get the details of all records.
  Let’s have a look at the profiling information.
DSC0003.png

  Though the absolute figures are not significant since they depend on the platform and runtime conditions, you will get an idea about relative cost of different functions. Notice that some functions are called hundreds of times (which is bad of course). The code doesn’t need to loop through all of the orders and get the details of each order individually. Let’s rewrite the getAll() function to use a JOIN instead.


1

2

3

4

5

6

7

8

9

10

11

12

13


<?php

pubilc function getAll() {


    $orders = array();


    $query = "SELECT * FROM orders o


        JOIN orderdetails d ON o.orderId = od.Id


        ORDER BY o.orderId


        ";


    $result = $this->db->query($query);


    while($row =$result->fetch(PDO::FETCH_ASSOC)){


        $orders[] = $row;


    }


    return $orders;


}







  Now the profiling yields a better result since the number of queries has decreased. Also, the code isn’t calling the getDetails() function any more.
DSC0004.png


Summary
  Xdebug act as a middleman that controls the execution of PHP programs in the server. In this article you’ve seen two of the most impressive features of Xdebug – debugging support and profiling support.
  Its remote debugging allows you to inspect values at runtime, without modifying your program, to get a better understanding of what PHP is doing. Profiling helps uncover bottlenecks in your code so you can optimize it for better performance.
  I hope this article helps you realize the benefits of Xdebug and encourages you to start using it right away if you aren’t already. And if you find this a valuable tool, you might even want to consider supporting this great project by buying a support agreement.

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-358353-1-1.html 上篇帖子: PHP垃圾回收机制的理解 下篇帖子: 提高PHP代码质量36计
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表