使用 Linux Perf

¥Using Linux Perf

Linux Perf 使用 JavaScript、原生和操作系统级框架提供底层 CPU 分析。

¥Linux Perf provides low level CPU profiling with JavaScript, native and OS level frames.

重要:本教程仅适用于 Linux。

¥Important: this tutorial is only available on Linux.

如何

¥How To

Linux Perf 通常可通过 linux-tools-common 包获得。通过 --perf-basic-prof--perf-basic-prof-only-functions,我们可以启动支持 perf_events 的 Node.js 应用。

¥Linux Perf is usually available through the linux-tools-common package. Through either --perf-basic-prof or --perf-basic-prof-only-functions we are able to start a Node.js application supporting perf_events.

--perf-basic-prof 将始终写入文件 (/tmp/perf-PID.map),这可能导致磁盘无限增长。如果担心这一点,请使用模块:linux-perf--perf-basic-prof-only-functions

¥--perf-basic-prof will always write to a file (/tmp/perf-PID.map), which can lead to infinite disk growth. If that’s a concern either use the module: linux-perf or --perf-basic-prof-only-functions.

两者之间的主要区别在于 --perf-basic-prof-only-functions 产生的输出较少,它是生产分析的可行选择。

¥The main difference between both is that --perf-basic-prof-only-functions produces less output, it is a viable option for production profiling.

# Launch the application an get the PID
$ node --perf-basic-prof-only-functions index.js &
[1] 3870

然后根据所需频率记录事件:

¥Then record events based in the desired frequency:

$ sudo perf record -F 99 -p 3870 -g

在此阶段,你可能希望在应用中使用负载测试,以便生成更多记录以进行可靠的分析。当作业完成后,通过向命令发送 SIGINT(Ctrl-C)来关闭 perf 进程。

¥In this phase, you may want to use a load test in the application in order to generate more records for a reliable analysis. When the job is done, close the perf process by sending a SIGINT (Ctrl-C) to the command.

perf 将在 /tmp 文件夹中生成一个文件,通常称为 /tmp/perf-PID.map(在上面的示例中为:/tmp/perf-3870.map),其中包含每个调用函数的跟踪。

¥The perf will generate a file inside the /tmp folder, usually called /tmp/perf-PID.map (in above example: /tmp/perf-3870.map) containing the traces for each function called.

要将这些结果汇总到特定文件中,请执行:

¥To aggregate those results in a specific file execute:

$ sudo perf script > perfs.out

原始输出可能有点难以理解,因此通常使用原始文件来生成火焰图以获得更好的可视化效果。

¥The raw output can be a bit hard to understand so typically the raw file is used to generate flamegraphs for a better visualization.

Example nodejs flamegraph

要从此结果生成火焰图,请按照步骤 6 中的 本教程 进行操作。

¥To generate a flamegraph from this result, follow this tutorial from step 6.

由于 perf 输出不是 Node.js 专用工具,因此它可能与 Node.js 中 JavaScript 代码的优化方式存在问题。有关进一步参考,请参阅 perf 输出问题

¥Because perf output is not a Node.js specific tool, it might have issues with how JavaScript code is optimized in Node.js. See perf output issues for a further reference.

有用的链接

¥Useful Links

阅读时间
3 min
目录
  1. 如何
  2. 有用的链接