使用perf工具分析rust代码运行性能

前言

  perf内置于Linux内核源码树中的系统性能剖析(profiling)工具,原理是在CPU的PMU register中Get/Set performance counters来获得诸如instructions executed,cache-missed suffered,branches mispredicted等信息。如果您使用的是其他操作系统,则可以使用其他工具(例如 valgrind)来分析 Rust 代码的性能。

正文
  perf 是一种常用的 Linux 性能分析工具,可用于分析 Rust 程序的性能。要使用 perf 分析 Rust 代码,您需要执行以下步骤: 

  1. 安装 perf:在终端中输入 sudo apt-get install linux-tools-common 即可安装 perf 工具。(如果你在安装好perf之后发现perf会报如下错误,可以使用sudo apt-get install linux-tools-$(uname -r)命令将缺少的东西安装)

    1 WARNING: perf not found for kernel 3.16.0-45
    2 
    3   You may need to install the following packages for this specific kernel:
    4     linux-tools-3.16.0-45-generic
    5     linux-cloud-tools-3.16.0-45-generic
    6 
    7   You may also want to install one of the following packages to keep up to date:
    8     linux-tools-generic
    9     linux-cloud-tools-generic
  2. 编译 Rust 代码:使用 cargo build --release 编译 Rust 代码,以便生成可执行文件。

  3. 运行 perf:在终端中输入以下命令以使用 perf 分析 Rust 代码:

    1 perf record target/release/your-program
  4. 生成报告:输入以下命令以生成性能报告:
    1 perf report

  这会生成一份详细的报告,按函数名称排序,显示哪些函数消耗了最多时间。您可以使用此报告来了解哪些函数可能导致性能问题,并确定如何解决这些问题。

 注意,perf 仅适用于 Linux 系统,并且需要在发布模式(--release)下编译 Rust 代码,才能生成可执行文件。

例:下图是我是用perf分析一个应用程序所生成的报告图:

 

posted @ 2022-12-22 10:28  莴苣&  阅读(591)  评论(0编辑  收藏  举报