Linux下gprof和oprofiling性能测试工具

一、简介

有些时候,我们特别关注程序的性能,特别是底层软件,比如驱动程序,OS等。为了更好的优化程序性能,我们必须找到性能瓶颈点,“好钢用在刀刃上”才能取 得好的效果,否则可能白做工作。为了找到关键路径,我们可以使用profilng技术,在linux平台上,我们可以使用gprof和oprofile工 具。

gprof是GNU工具之一,它在编译的时候在每个函数的出入口加入了profiling的代码,运行时统计程序在用户态的 执行信息,可以得到每个函数的调用次数,执行时间,调用关系等信息,简单易懂。适合于查找用户级程序的性能瓶颈,对于很多时间都在内核态执行的程 序,gprof不适合。

oProfile是Linux平台上的一个功能强大的性能分析工具,支持两种采样(sampling)方式:基于事件的采样(eventbased)和基于时间的采样(timebased),它可以工作在不同的体系结构上,包括MIPS、ARM、IA32、IA64和AMD。

二、gprof使用方法

gprof是gnu binutils工具之一,默认情况下linux系统当中都带有这个工具

使用 -pg 选项来编译hello.c,如果要得到带注释的源码清单,则需要增加 -g 选项。运行: gcc -pg -g -o hello hello.c
运行应用程序: ./hello 会在当前目录下产生gmon.out文件,使用gprof来分析gmon.out文件时,需要把它和产生它的应用程序关联起来:

gprof hello gmon.out -p 得到每个函数占用的执行时间 
gprof hello gmon.out -q 得到call graph,包含了每个函数的调用关系,调用次数,执行时间等信息。 
gprof hello gmon.out -A 得到 一个带注释的“源代码清单”,它会注释源码,指出每个函数的执行次数。这需要在编译的时候增加 -g选项。

三、oprofile安装步骤

1、打开内核OPROFILE选项,否则运行oProfile将提示:

[root@localhost oprofile-0.9.6]# opcontrol --init 
FATAL: Module oprofile not found. 
FATAL: Module oprofile not found. 
Kernel doesn't support oprofile
2、编辑内核配置文件:.config,将其中的# CONFIG_OPROFILE is not set改为CONFIG_OPROFILE=m(或者y) 
[root@localhost ~]# cd /usr/src/linux-2.6.37.2 
[root@localhost linux-2.6.37.2]# vi .config

如下:

CONFIG_PROFILING=y 
CONFIG_X86_LOCAL_APIC=y 
CONFIG_X86_IO_APIC=y 
CONFIG_PCI_IOAPIC=y

3、编译内核并重启机器

4、下载源码,编译安装

wget http://cznic.dl.sourceforge.net/project/oprofile/oprofile/oprofile-1.0.0/oprofile-1.0.0.tar.gz
tar -zxvf oprofile-1.0.0.tar.gz
cd oprofile-1.0.0
./configure
make
make install

四、oprofile工具集

op_help:    列出所有支持的事件。
opcontrol:  设置需要收集的事件。
opreport:  对结果进行统计输出。
opannaotate:产生带注释的源/汇编文件,源语言级的注释需要编译源文件时的支持。
opstack:    产生调用图profile,但要求x86/2.6的平台,并且linux2.6安装了call-graph patch
opgprof:    产生如gprof相似的结果。
oparchive:  将所有的原始数据文件收集打包,可以到另一台机器上进行分析。
op_import:  将采样的数据库文件从另一种abi转化成本地格式。

五、oprofile使用方法

测试文件:multiply.c

#include <stdio.h> 
int fast_multiply(x,  y) 

    return x * y; 

  
int slow_multiply(x, y) 

    int i, j, z; 
    for (i = 0, z = 0; i < x; i++) 
        z = z + y; 
    return z; 

  
int main(int argc, char *argv[]) 

    int i,j; 
    int x,y; 
    for (i = 0; i < 200; i ++) { 
        for (j = 0; j <  30 ; j++) { 
            x = fast_multiply(i, j); 
            y = slow_multiply(i, j); 
        } 
    } 
    printf("x=%d, y=%d ", x, y); 
    return 0; 
}

编译

gcc multiply.c -g -o multiply

测试

modprobe oprofile timer=1 
opcontrol --no-vmlinux
opcontrol --separate=kernel
opcontrol --init 
opcontrol --reset 
opcontrol --start
./multiply
opcontrol --dump
opcontrol --stop
opcontrol --shutdown
opcontrol --deinit
opannotate --source ./multiply


opreport -l ./multiply


opreport

本文永久更新链接地址http://www.linuxidc.com/Linux/2015-06/118874.htm

原文地址:https://www.cnblogs.com/smilingsusu/p/12836030.html