XHProf Documentation (译)


#1

XHProf Documentation (译)


##1. Introduction //简介

XHProf is a hierarchical profiler for PHP.
XHProf 是一个分层的 PHP 分析器

It reports function-level call counts and inclusive and exclusive metrics such as wall (elapsed) time, CPU time and memory usage.
它可以记录函数级别的调用次数和函数包含子孙函数的执行时间以及不包含子孙函数本身的执行时间,CPU 时间和内存使用.

A function's profile can be broken down by callers or callees.
一个函数从剖析角度可以被看作调用者 或 被调用者

The raw data collection component is implemented in C as a PHP Zend extension called xhprof.
源数据收集部分是一个由C写的PHP扩展

XHProf has a simple HTML based user interface (written in PHP).
XHProf有一个简单的基于HTML的用户界面(用PHP写的)。

The browser based UI for viewing profiler results makes it easy to view results or to share results with peers.
基于浏览器的界面可以更容易的查看分析结果或与同事分享结果

A callgraph image view is also supported.
也可以查看调用关系图

XHProf reports can often be helpful in understanding the structure of the code being executed.
XHProf报告通常可以帮助理解正被执行的代码的结构。

The hierarchical nature of the reports can be used to determine,
报表分层的特性可以更容易的发现问题

for example, what chain of calls led to a particular function getting called.
例如,调用链条调用了一个特殊的函数

XHProf supports ability to compare two runs (a.k.a. "diff" reports) or aggregate data from multiple runs.
XHProf 支持对比两次 run 结果,也支持聚合多次 run 数据.

Diff and aggregate reports, much like single run reports, offer "flat" as well as "hierarchical" views of the profile.
Diff(对比) 和 aggregate(聚合) 报表,看起来就像单独的run报表一样,即可以扁平化查看也可以分层级查看

XHProf is a light-weight instrumentation based profiler.
XHProf 是一个轻量级基于仪表的分析器

During the data collection phase,
在数据收集阶段

it keeps track of call counts and inclusive metrics for arcs in the dynamic callgraph of a program.
它可以追踪函数调用次数和函数包含子孙函数的执行时间并用于动态生成程序的调用关系图

It computes exclusive metrics in the reporting/post processing phase.
在数据处理阶段可以计算出函数不包含子孙函数的 本身的执行时间

XHProf handles recursive functions by detecting cycles in the callgraph at data collection time itself
XHProf 通过数据采集的本身时间在调用关系图中检查循环来处理递归函数

and avoiding the cycles by giving unique depth qualified names for the recursive invocations.
并且避免了递归调用中循环产生的唯一深度的限定名

XHProf's light-weight nature and aggregation capabilities
XHProf的轻量级特性和聚合能力

make it well suited for collecting "function-level" performance statistics from production environments.
使它可以很好的用于生产环境来收集函数级别的性能统计数据

[See additional notes for use in production.]
可以去看用于生产的补充描述(这里指的是第六条)

XHProfLive (not part of the open source kit), for example,
XHProfLive (不是开源工具集的部分)

is a system-wide performance monitoring system in use at Facebook that is built on top of XHProf. 
是一个全系统的性能监控系统用于Facebook, 构建于XHProf之上

XHProfLive continually gathers function-level profiler data from production tier by running a sample of page requests under XHProf. 
XHProfLive 从生产层在XHProf下运行一个简单的页面请求,不断地收集函数级别的剖析数据

XHProfLive then aggregates the profile data corresponding to individual requests by various dimensions such a time, page type, 
然后聚合这些剖析数据并对应到各种维度的个体请求,页面类型

and can help answer a variety of questions such as: 
并且可以帮助你找到各种问题的答案

What is the function-level profile for a specific page?
特定页面的函数层次剖析?

How expensive is function "foo" across all pages, or on a specific page? 
函数 “foo” 在所有被调用的页面或特定页面的性能损耗怎么样?

What functions regressed most in the last hour/day/week? 
在最近一小时/天/周 的函数性能追踪?

What is the historical trend for execution time of a page/function? and so on.
一个页面/函数执行时间的历史趋向? 等等.

Originally developed at Facebook, XHProf was open sourced in Mar, 2009.
XHProf最初开发于 Facebook, 在2009年3月被开源

##2. XHProf Overview //XHProf 概述
XHProf provides: //XHProf 提供的有:

  • Flat profile //直观的剖析(截图)
    Provides function-level summary information such number of calls, inclusive/exclusive wall time, memory usage, and CPU time.
    提供函数级别的概要信息比如调用次数,包含子孙函数的执行时间/不包含子孙函数本身的执行时间,内存使用,CPU 时间。

  • Hierarchical profile (Parent/Child View) //有层级的剖析(父/子 视图) (截图)
    For each function, it provides a breakdown of calls and times per parent (caller) & child (callee), such as:
    为每个函数都提供了调用的breakdown(可以理解为包含执行时间等信息的表)和每次相关的父(调用者)子(被调用者)函数

    • what functions call a particular function and how many times?
      什么函数调用了一个特定的函数,调用了多少次?
    • what functions does a particular function call?
      特定的函数调用了什么函数?
    • The total time spent under a function when called from a particular parent.
      当从一个特定的父函数下被调用的子函数花费的时间
  • Diff Reports //对比报告
    You may want to compare data from two XHProf runs for various reasons–
    由于各种原因你可能想要比较两次 XHProf 运行的数据 –

    to figure out what’s causing a regression between one version of the code base to another,
    比如你可能想 找出是什么原因引起的一个版本代码库与另一个代码库之间的差异

    to evaluate the performance improvement of a code change you are making, and so on.
    再比如评估你要修改代码的性能改进,等等诸如此类问题

    A diff report takes two runs as input and provides both flat function-level diff information,
    diff报告有两个运行作为输入,并同时提供平面函数层次差异的信息

    and hierarchical information (breakdown of diff by parent/children functions) for each function.
    和分层信息(父/子函数breakdown的diff)为每一个函数

    The “flat” view (截图) in the diff report points out the top regressions & improvements.
    这种在diff报告中的 “平面化” 的视图可以指出是退化还是改进

    Clicking on functions in the “flat” view of the diff report,
    点击“平面化”视图的函数差异报告

    leads to the “hierarchical” (or parent/child) diff view of a function (截图).
    将转至“分层的”(或父/子)的diff函数视图

    We can get a breakdown of the diff by parent/children functions.
    我们可以通过函数的父子关系得到一个diff的breakdown

  • Callgraph View //调用关系图(截图)
    The profile data can also be viewed as a callgraph.
    剖析的数据可以被显示为一个调用关系图

    The callgraph view highlights the critical path of the program.
    调用关系图高亮的显示了程序的关键路径

  • Memory Profile //内存剖析
    XHProf’s memory profile mode helps track functions that allocate lots of memory.
    XHProf 的内存剖析模式可以帮助追踪函数分配了多少内存

    It is worth clarifying that that XHProf doesn’t strictly track each allocation/free operation.
    值得说明的是XHProf 并不严格追踪每个分配/释放内存的操作

    Rather it uses a more simplistic scheme.
    相反,它使用一个更简单的方案。

    It tracks the increase/decrease in the amount of memory allocated to PHP between each function’s entry and exit.
    它追踪PHP每个函数的入口和出口之间的内存分配数量的增加/减少

    It also tracks increase/decrease in the amount of peak memory allocated to PHP for each function.
    它也可以追踪PHP每个函数内存分配峰值的数量的增加/减少

  • XHProf tracks include, include_once, require and require_once operations as if they were functions.
    XHProf 追踪 include, include_once, require 和 require_once 之类的函数

    The name of the file being included is used to generate the name for these “fake” functions.
    将文件名包含在其中被用于生成这些 “伪” 函数名

Terminology 技术术语

  1. Inclusive Time (or Subtree Time): Includes time spent in the function as well as in descendant functions called from a given function.
    Inclusive time (or Subtree Time): 函数的执行时间包含了子孙函数的执行时间
  2. Exclusive Time/Self Time: Measures time spent in the function itself. Does not include time in descendant functions.
    Exclusive Time/Self Time: 函数本身的执行时间,不包含子孙函数的执行时间
  3. Wall Time: a.k.a. Elapsed time or wall clock time.
    Wall Time: 执行当前任务所花费的总时间或墙上时间(CPU Time 指的是CPU在忙于执行当前任务的时间,其并没有考虑等待时间,如IO等待,网络等待等,而Elapsed Time 则是执行当前任务所花费的总时间,两者之
    问的关系统可以表示为 Elapsed Time = Cpu Time + Wait Time 但是在多核处理器的情况下,由于多个CPU同时处理任务所以可能会出现Cpu Time 大于Elapsed Time 的情况)
  4. CPU Time: CPU time in user space + CPU time in kernel space
    CPU Time: 进程执行用户模式下代码所使用的时间+进程在内核中所花费的CPU时间

Naming convention for special functions 特定函数的命名规则

  1. main(): a fictitious function that is at the root of the call graph.
    main(): 一个虚构的函数,在调用图的根节点

  2. load::<filename> and run_init::<filename>:
    XHProf tracks PHP include/require operations as function calls.
    XHProf 追踪 PHP include/require 操作作为函数调用

    For example, an include "lib/common.php"; operation will result in two XHProf function entries:
    例如,一个 include “lib/common.php”; 操作将产生两条 XHProf 记录

  • load::lib/common.php - This represents the work done by the interpreter to compile/load the file.
    load::lib/common.php - 表示通过解释器去 ‘编译/载入’ 这个文件完成.
    [Note: If you are using a PHP opcode cache like APC, then the compile only happens on a cache miss in APC.]
    [注意:如果你使用像APC这样的PHP opcode 缓存,那么’编译’仅仅发生在APC缓存丢失的时候]

  • run_init::lib/common.php - This represents initialization code executed at the file scope as a result of the include operation.
    run_init::lib/common.php - 表示所在文件作用域的初始化代码已执行,这作为 include 操作其中的一个结果

  1. foo@<n>: Implies that this is a recursive invocation of foo(), where represents the recursion depth.
    foo@<n>:意味着这是 foo() 的递归调用, <n> 表示递归的深度.
    The recursion may be direct (such as due to foo() --> foo()), or indirect (such as due to foo() --> goo() --> foo()).
    这个递归可能是直接的(类似 foo() --> foo()),或者间接的 (foo() --> goo() --> foo())

Limitations 局限性

True hierarchical profilers keep track of a full call stack at every data gathering point, and are later able to answer questions like:
一个完整的调用栈在每一个数据收集点持续的追踪可以回答我们下面的问题

what was the cost of the 3rd invokation of foo()?
foo() 函数的第三次调用花费了多少资源?

or what was the cost of bar() when the call stack looked like a()->b()->bar()?
或者当调用栈类似于 a()->b()->bar() 中 bar() 花费了多少资源?

XHProf keeps track of only 1-level of calling context and is therefore only able to answer questions about a function looking either 1-level up or 1-level down.
XHProf 持续追踪仅仅只有1级调用的上下文,仅仅能够回答关于一个函数的上一级或下一级的问题

It turns out that in practice this is sufficient for most use cases.
事实证明,在实践中对于大多数用例这已经足够了。

To make this more concrete, take for instance the following example.
看看下面更具体的例子

Say you have:
1 call from a() --> c()
1 call from b() --> c()
50 calls from c() --> d()

While XHProf can tell you that d() was called from c() 50 times,
XHProf 可以告诉你 d() 被 c() 调用了50次

it cannot tell you how many of those calls were triggered due to a() vs. b().
但是它不能告诉你这其中有多少次是由 a() 和 b() 触发的

[We could speculate that perhaps 25 were due to a() and 25 due to b(), but that’s not necessarily true.]
[我们可以推测也许a()触发了25次,b() 触发了 25 次,但是这并不一定是真实情况]

In practice however, this isn’t a very big limitation.
在实践中,这并不是一个非常大的局限性

##3. Installing the XHProf Extension //安装XHProf扩展
The extension lives in the “extension/” sub-directory.
扩展存在于 “extension/” 子目录

Note: A windows port hasn't been implemented yet. We have tested xhprof on Linux/FreeBSD so far.
注意:windows版还没有实现,我们目前为止只在 Linux/FreeBSD 上测试过

Version 0.9.2 and above of XHProf is also expected to work on Mac OS. [We have tested on Mac OS 10.5.]
XHProf 0.9.2 以上版本预期可以工作在 MacOS 上[ 我们在 MacOS 10.5 上测试过 ]

Note: XHProf uses the RDTSC instruction (time stamp counter) to implement a really low overhead timer for elapsed time. 
注意:XHProf使用RDTSC指令(时间戳计数器)实现一个真正的低开销计时器运行时间

So at the moment xhprof only works on x86 architecture. 
所以目前 xhprof 只适合在 x86 架构下工作

Also, since RDTSC values may not be synchronized across CPUs, xhprof binds the program to a single CPU during the profiling period.
另外,由于 RDTSC 值可能与CPU不是同步的, xhprof 会绑定到一个单独的CPU上进行性能分析

XHProf's RDTSC based timer functionality doesn't work correctly if SpeedStep technology is turned on. 
XHProf 的 RDTSC 基于计时器功能,如果 SpeedStep 打开,它是不工作的

This technology is available on some Intel processors. 
SpeedStep 技术在一些处理器是可以启用的

[Note: Mac desktops and laptops typically have SpeedStep turned on by default. To use XHProf, you'll need to disable SpeedStep.]
[注意:Mac 桌面电脑和笔记本电脑默认会开启 SpeedStep. 如果使用 XHProf 你需要关闭 SpeedStep]

The steps below should work for Linux/Unix environments.
按照下面的安装步骤 可以工作在 Linux/Unix 环境上

% cd <xhprof_source_directory>/extension/
% phpize
% ./configure --with-php-config=<path to php-config>
% make
% make install
% make test

php.ini file: You can update your php.ini file to automatically load your extension. Add the following to your php.ini file.
php.ini file: 你可以修改你的 php.ini 文件自动加载你的扩展. 添加下面的内容到你的 php.ini 文件

[xhprof]
extension=xhprof.so
;
; directory used by default implementation of the iXHProfRuns
; interface (namely, the XHProfRuns_Default class) for storing
; XHProf runs.
;
xhprof.output_dir=<directory_for_storing_xhprof_runs> //保存 xhprof_runs 数据的目录

##4. Profiling using XHProf //用XHProf Profiling
Test generating raw profiler data using a sample test program like:
用一个简单的测试程序测试生成源数据:

foo.php

<?php

function bar($x) {
  if ($x > 0) {
    bar($x - 1);
  }
}

function foo() {
  for ($idx = 0; $idx < 2; $idx++) {
    bar($idx);
    $x = strlen("abc");
  }
}

// start profiling
xhprof_enable();

// run program
foo();

// stop profiler
$xhprof_data = xhprof_disable();

// display raw xhprof data for the profiler run
print_r($xhprof_data);

Run the above test program: //运行上面的测试程序:

% php -dextension=xhprof.so foo.php

You should get an output like: //你应该可以得到下面的输出

Array
(
    [foo==>bar] => Array
        (
            [ct] => 2         # 2 calls to bar() from foo()
            [wt] => 27        # inclusive time in bar() when called from foo()
        )

    [foo==>strlen] => Array
        (
            [ct] => 2         # strlen() 被 foo() 调用了2次
            [wt] => 2         # 当 foo() 调用 strlen() 时的 inclusive time
        )

    [bar==>bar@1] => Array    # a recursive call to bar() //一个递归调用
        (
            [ct] => 1
            [wt] => 2
        )

    [main()==>foo] => Array
        (
            [ct] => 1
            [wt] => 74
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 0
        )

    [main()] => Array         # fake symbol representing root //'伪'函数名(main)表示根节点
        (
            [ct] => 1
            [wt] => 83
        )
)

Note: The raw data only contains “inclusive” metrics.
注意:这个源数据仅仅包含 “inclusive”(表示包含子孙函数执行时间) 数据.

For example, the wall time metric in the raw data represents inclusive time in microsecs.
也就是说,源数据中只有微秒级别的 inclusive 时间.

Exclusive times for any function are computed during the analysis/reporting phase.
Exclusive(函数本身的执行时间) 时间是从 分析/生成报表 阶段从函数中计算出来的

Note: By default only call counts & elapsed time is profiled.
注意:默认仅仅能获取到调用次数和函数花费的总时间

You can optionally also profile CPU time and/or memory usage. Replace,
你也可以选择添加 CPU time 和 内存使用 数据。

xhprof_enable();

in the above program with, for example: //将上面的代码修改为下面这样

xhprof_enable(XHPROF_FLAGS_CPU + XHPROF_FLAGS_MEMORY);

You should now get an output like: //你就会得到下面的输出:

Array
(
    [foo==>bar] => Array
        (
            [ct] => 2     # number of calls to bar() from foo()
            [wt] => 37    # time in bar() when called from foo()
            [cpu] => 0    # cpu time in bar() when called from foo()
            [mu] => 2208  # change in PHP memory usage in bar() when called from foo()
            [pmu] => 0    # change in PHP peak memory usage in bar() when called from foo()
        )

    [foo==>strlen] => Array
        (
            [ct] => 2     # foo() 调用 strlen() 的次数
            [wt] => 3     #当 foo() 调用 strlen() 时的 inclusive time
            [cpu] => 0    #当 foo() 调用 strlen() 时的 cpu time
            [mu] => 624   #当 foo() 调用 strlen() 时 PHP 内存使用量的变化
            [pmu] => 0    #当 foo() 调用 strlen() 时 PHP 内存使用峰值的变化
        )

    [bar==>bar@1] => Array
        (
            [ct] => 1
            [wt] => 2
            [cpu] => 0
            [mu] => 856
            [pmu] => 0
        )

    [main()==>foo] => Array
        (
            [ct] => 1
            [wt] => 104
            [cpu] => 0
            [mu] => 4168
            [pmu] => 0
        )

    [main()==>xhprof_disable] => Array
        (
            [ct] => 1
            [wt] => 1
            [cpu] => 0
            [mu] => 344
            [pmu] => 0
        )

    [main()] => Array
        (
            [ct] => 1
            [wt] => 139
            [cpu] => 0
            [mu] => 5936
            [pmu] => 0
        )
)

Skipping builtin functions during profiling //跳过PHP内置API执行时间的抓取

By default PHP builtin functions (such as strlen) are profiled.
默认会抓取PHP内置函数(例如strlen()这种函数)数据的

If you do not want to profile builtin functions (to either reduce the overhead of profiling further or size of generated raw data), you can use the XHPROF_FLAGS_NO_BUILTINS flag as in for example:
如果你不想剖析这种内置函数(进一步降低剖析的开销或生成的原始数据的大小),你可以用 XHPROF_FLAGS_NO_BUILTINS

// do not profile builtin functions
xhprof_enable(XHPROF_FLAGS_NO_BUILTINS);

Ignoring specific functions during profiling (0.9.2 or higher) //忽略指定方法的时间抓取(0.9.2以上版本)

Starting with release 0.9.2 of xhprof, you can tell XHProf to ignore a specified list of functions during profiling.
xhprof从0.9.2版本开始,你可以告诉 XHProf 忽略剖析特定的方法列表

This allows you to ignore, for example, functions used for indirect function calls such as call_user_func and call_user_func_array.
比如你可以忽略 call_user_func 和 call_user_func_array 这种间接的方法调用剖析

These intermediate functions unnecessarily complicate the call hierarchy and make the XHProf reports harder to interpret since they muddle the parent-child relationship for functions called indirectly.
这些中间不必要的函数使调用层次结构更加复杂,也使XHProf报告难以分析,因为他们间接调用函数使父子关系混乱。

To specify the list of functions to be ignored during profiling use the 2nd (optional) argument to xhprof_enable. For example,
指定需要忽略剖析的函数列表可以使用 xhprof_enable 的第二个参数

// elapsed time profiling; ignore call_user_func* during profiling
xhprof_enable(0,
             array('ignored_functions' =>  array('call_user_func',
                                                 'call_user_func_array')));

or,

// elapsed time + memory profiling; ignore call_user_func* during profiling
xhprof_enable(XHPROF_FLAGS_MEMORY,
              array('ignored_functions' =>  array('call_user_func',
                                                  'call_user_func_array')));

##5. Setting up XHProf UI //配置 XHProf UI

1. PHP source structure //PHP源码结构
The XHProf UI is implemented in PHP. The code resides in two subdirectories, xhprof_html/ and xhprof_lib/.
XHProf UI 使用PHP实现.代码存在于两个子目录里, xhprof_html/ 和 xhprof_lib/

The xhprof_html directory contains the 3 top-level PHP pages.
xhprof_html 目录包含 3个顶级 PHP 页面

  • index.php: For viewing a single run or diff report.
    index.php 用于查看一次运行的或 diff 的报表

  • callgraph.php: For viewing a callgraph of a XHProf run as an image.
    callgraph.php 用于查看调用关系图

  • typeahead.php: Used implicitly for the function typeahead form on a XHProf report.
    typeahead.php 用于暗中预处理 XHProf 报表

    The xhprof_lib directory contains supporting code for display as well as analysis
    xhprof_lib 目录包含用于支持显示和分析的代码

    (computing flat profile info, computing diffs, aggregating data from multiple runs, etc.).
    计算平面剖析信息,计算两次运行差异,聚合来自多次运行的数据等。

2. Web server config: //Web Server 配置
You’ll need to make sure that the xhprof_html/ directory is accessible from your web server, and that your web server is setup to serve PHP scripts.
你需要确保 xhprof_html/ 目录是可以从你的 Web Server 访问的,并且你的 Web Server 是可以运行PHP脚本的

3. Managing XHProf Runs //管理 XHProf 运行

Clients have flexibility in how they save the XHProf raw data obtained from an XHProf run.
客户可以灵活设置从一个 XHProf run 获取的 XHProf 源数据的保存位置

The XHProf UI layer exposes an interface iXHProfRuns (see xhprof_lib/utils/xhprof_runs.php) that clients can implement.
XHProf UI 层暴露一个 iXHProfRuns 接口 (看 xhprof_lib/utils/xhprof_runs.php),用户可以实现它

This allows the clients to tell the UI layer how to fetch the data corresponding to a XHProf run.
这允许用户告诉 UI 层,怎样从相应的 XHProf run 中获取数据

The XHProf UI libaries come with a default file based implementation of the iXHProfRuns interface, namely “XHProfRuns_Default” (also in xhprof_lib/utils/xhprof_runs.php).
XHProf UI 库有一个基于 iXHProfRuns 接口实现的默认文件 ,名字类似为 “XHProfRuns_Default” (同样也在 xhprof_lib/utils/xhprof_runs.php 文件中)

This default implementation stores runs in the directory specified by xhprof.output_dir INI parameter.
这个默认的实现将数据保存在 xhprof.output_dir ini 参数指定的目录中

A XHProf run must be uniquely identified by a namespace and a run id.
一个 XHProf run 必须有 命名空间中的唯一的标识和 run id

a) Saving XHProf data persistently: //持续地保存 XHProf 数据

Assuming you are using the default implementation XHProfRuns_Default of the iXHProfRuns interface,
假设你用 iXHProfRuns 接口的默认实现 XHProfRuns_Default

a typical XHProf run followed by the save step might look something like:
一个典型的 XHProf 运行的步骤类似于下面

<?php
// start profiling
xhprof_enable();

// run program
....

// stop profiler
$xhprof_data = xhprof_disable();

//
// Saving the XHProf run
// using the default implementation of iXHProfRuns.
//
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_lib.php";
include_once $XHPROF_ROOT . "/xhprof_lib/utils/xhprof_runs.php";

$xhprof_runs = new XHProfRuns_Default();

// Save the run under a namespace "xhprof_foo".
//
// **NOTE**:
// By default save_run() will automatically generate a unique
// run id for you. [You can override that behavior by passing
// a run id (optional arg) to the save_run() method instead.]
//
$run_id = $xhprof_runs->save_run($xhprof_data, "xhprof_foo");

echo "---------------\n".
     "Assuming you have set up the http based UI for \n".
     "XHProf at some address, you can view run at \n".
     "http://<xhprof-ui-address>/index.php?run=$run_id&source=xhprof_foo\n".
     "---------------\n";

The above should save the run as a file in the directory specified by the xhprof.output_dir INI parameter.
上面的 run 结果会作为一个文件保存在 php.ini 里配置的 xhprof.output_dir 指定的目录中

The file’s name might be something like 49bafaa3a3f66.xhprof_foo;
这个文件的名字可能类似于 49bafaa3a3f66.xhprof_foo;

the two parts being the run id (“49bafaa3a3f66”) and the namespace (“xhprof_foo”).
文件名的两个部分是 run_id (“49bafaa3a3f66”) 和 命名空间 (“xhprof_foo”).

If you want to create/assign run ids yourself (such as a database sequence number, or a timestamp),
如果你想 创建/分配 你自己的 run id (比如 数据库序列号,或时间戳)

you can explicitly pass in the run id to the save_run method.
你可以使用 save_run 方法(该方法的第三个参数可以设置run_id),明确的指定 run_id

b) Using your own implementation of iXHProfRuns //使用你自己实现的iXHProfRuns接口

If you decide you want your XHProf runs to be stored differently (either in a compressed format, in an alternate place such as DB, etc.) database, you’ll need to implement a class that implements the iXHProfRuns() interface.
如果你决定你想要你的XHProf runs使用不同的存储(压缩格式,或在另一个地方比如数据库,等等)数据库,你需要通过实现iXHProfRuns()接口去实现一个类

You’ll also need to modify the 3 main PHP entry pages (index.php, callgraph.php, typeahead.php) in the “xhprof_html/” directory to use the new class instead of the default class XHProfRuns_Default.
你将需要修改 “xhprof_html/” 目录中的 3个主要的 php 入口页面,用新的类代替 默认类 XHProfRuns_Default

Change this line in the 3 files.
在这三个文件中修改下面这行代码.

$xhprof_runs_impl = new XHProfRuns_Default();

You’ll also need to “include” the file that implements your class in the above files.
你还需要在上面的文件中 “include” 你实现的类文件。

4. Accessing runs from UI //从 UI 访问 runs
a) Viewing a Single Run Report //查看一次单独运行的报告

To view the report for run id say <run_id> and namespace <namespace> use a URL of the form:
查看这个报告需要用 run_id 和 namespace 替换下面形式 url的 <run_id><namespace>

http://<xhprof-ui-address>/index.php?run=<run_id>&source=<namespace>

For example,

http://<xhprof-ui-address>/index.php?run=49bafaa3a3f66&source=xhprof_foo

b) Viewing a Diff Report //查看两次结果的对比报告

To view the report for run ids say <run_id1> and <run_id2> in namespace <namespace> use a URL of the form:

http://<xhprof-ui-address>/index.php?run1=<run_id1>&run2=<run_id2>&source=<namespace>

c) Aggregate Report //聚合报告

You can also specify a set of run ids for which you want an aggregated view/report.
你也可以指定一个 run id 集合聚合成一份你想要的聚合视图/报告

Say you have three XHProf runs with ids 1, 2 & 3 in namespace “benchmark”.
如果说你在命名空间 “benchmark” 有三个 XHProf run 的 id 为1,2,3

To view an aggregate report of these runs: //查看这些run的聚合报告可以访问下面形式的url

http://<xhprof-ui-address>/index.php?run=1,2,3&source=benchmark

Weighted aggregations: //按权重聚合
Further suppose that the above three runs correspond to three types of programs p1.php, p2.php and p3.php that typically occur in a mix of 20%, 30%, 50% respectively.
进一步假设上面的三次 run 对应三种类型的程序 p1.php, p2.php, p3.php ,执行的概率分别是 20%,30%,50%

To view an aggregate report that corresponds to a weighted average of these runs using:
查看这些对应权重聚合的 run 结果使用下面形式的url

http://<xhprof-ui-address>/index.php?run=1,2,3&wts=20,30,50&source=benchmark

##6. Notes on using XHProf in production //在生产环境使用 XHProf 的注意事项

Some observations/guidelines. Your mileage may vary:
一些观察结果/指导方向。 因人而异

  • CPU timer (getrusage) on Linux has high overheads.
    CPU计时器(getrusage函数)在Linux上具有较高的开销

    It is also coarse grained (millisec accuracy rather than microsec level) to be useful at function level.
    它是粗粒度的(毫秒级别的准确性,而不是微秒级别)在函数级别是有用的

    Therefore, the skew in reported numbers when using XHPROF_FLAGS_CPU mode tends to be higher.
    所以,当使用 XHPROF_FLAGS_CPU 模式时开销会升高

    We recommend using elapsed time + memory profiling mode in production.
    在生产环境我们推荐使用 elapsed time + memory 的分析模式

    [Note: The additional overhead of memory profiling mode is really low.]
    [注意: 内存分析模式的额外开销很低]

  // elapsed time profiling (default) + memory profiling
  xhprof_enable(XHPROF_FLAGS_MEMORY);
  • Profiling a random sample of pages/requests works well in capturing data that is representative of your production workload.
    分析随机 页面/请求 执行的样本数据就可以很好的分析出你在生产环境的工作负载

    To profile say 1/10000 of your requests, instrument the beginning of your request processing with something along the lines of:
    比如说剖析你 1/10000 的请求,在请求的开始,可以像下面这样写

 if (mt_rand(1, 10000) == 1) {
   xhprof_enable(XHPROF_FLAGS_MEMORY);
   $xhprof_on = true;
 }

At the end of the request (or in a request shutdown function), you might then do something like:
在请求的结尾你可以像下面这样写

 if ($xhprof_on) {
   // stop profiler
   $xhprof_data = xhprof_disable();

   // save $xhprof_data somewhere (say a central DB)
   ...
 }

You can then rollup/aggregate these individual profiles by time (e.g., 5 minutely/hourly/daily basis), page/request type,or other dimensions using xhprof_aggregate_runs().
使用 xhprof_aggregate_runs(). 你可以通过时间(比如基于 5分钟/小时/天),页面/请求类型,或其他规格 汇总/聚合一些分析数据

##7. Lightweight Sampling Mode //轻量级采样模式

The xhprof extension also provides a very light weight sampling mode. The sampling interval is 0.1 secs.
xhprof 扩展也提供了一个非常轻量级的采样模式. 每0.1秒采样一次

Samples record the full function call stack.
采样记录是全部的方法调用栈

The sampling mode can be useful if an extremely low overhead means of doing performance monitoring and diagnostics is desired.
如果需要在极低的开销下进行性能监控和诊断,采样模式是非常有用的

The relevant functions exposed by the extension for using the sampling mode are xhprof_sample_enable() and xhprof_sample_disable().
扩展中提供了用于采样模式相关的函数 xhprof_sample_enable() 和 xhprof_sample_disable()

##8. Additional Features //附加特性

The xhprof_lib/utils/xhprof_lib.php file contains additional library functions that can be used for manipulating/ aggregating XHProf runs.
xhprof_lib/utils/xhprof_lib.php 文件包含附加库函数能够被用于 操纵/聚合 XHProf run 结果

For example:

  • xhprof_aggregate_runs(): can be used to aggregate multiple XHProf runs into a single run.
    xhprof_aggregate_runs() 能够被用于聚合多次 XHProf run 结果到一次 run 结果中

    This can be helpful for building a system-wide “function-level” performance monitoring tool using XHProf.
    这使得 XHProf 有助于建立一个全系统的 “函数级别” 的性能监视工具。

    [For example, you might to roll up XHProf runs sampled from production periodically to generate hourly, daily, reports.]
    [例如,你可以积累 XHProf run 从生产环境定期采样的数据,从而生成每小时,每天的报告]

  • xhprof_prune_run(): Aggregating large number of XHProf runs (especially if they correspond to different types of programs) can result in the callgraph size becoming too large.
    xhprof_prune_run(): 聚合大量的 XHProf run 结果(尤其是聚合来自不同类型的程序)会导致 调用关系图变的太大

    You can use xhprof_prune_run function to prune the callgraph data by editing out subtrees that account for a very small portion of the total time.
    你可以使用 xhprof_prune_run 方法通过编辑子树去减少调用关系图中占用很小一部分时间的数据

##9. Dependencies //依赖

  • JQuery Javascript: For tooltips and function name typeahead, we make use of JQuery’s javascript libraries.
    JQuery Javascript: 工具提示和函数名预处理,我们利用JQuery javascript库。

    JQuery is available under both a MIT and GPL licencse (http://docs.jquery.com/Licensing).
    在 MIT 和 GPL 许可下使用 JQuery

    The relevant JQuery code, used by XHProf, is in the xhprof_html/jquery subdirectory.
    XHProf 相关的 JQuery 代码在 xhprof_html/jquery 子目录中

  • dot (image generation utility): The callgraph image visualization ([View Callgraph]) feature relies on the presence of Graphviz “dot” utility in your path.
    dot (image generation utility):调用关系图可视化特性依赖于你系统路径中的 Graphviz “dot” 程序

    “dot” is a utility to draw/generate an image for a directed graph.
    “dot” 是一个画/生成有向图像的程序

##10. Acknowledgements //后记

The HTML-based navigational interface for browsing profiler results is inspired by that of a similar tool that exists for Oracle’s stored procedure language, PL/SQL.
基于html的导航界面来浏览剖析结果是受 Oracle 的存储过程语言 PL/SQL 的启发

But that’s where the similarity ends;
但仅仅是相似而已

the internals of the profiler itself are quite different.
分析器的内部本身有很大的不同。