导航:[首页]->[cpp]->[GNU性能测试和代码覆盖率]

使用gprof做性能测试

void f1()                                                                                                                                  
{
    for(int i = 0;i<10000;i++)
    {   
        int f = 0;
        f++;
    }   
}
void f2()
{
    for(int i = 0;i<20000;i++)
    {   
        int f = 0;
        f++;
    }   
}
int main(int argc, char** argv) 
{
    for(int i = 0;i<10000;i++)
    {   
        f1();
        f2();
        f2();
    }   
    return 0;
}

g++ main.c -pg -g
./a.out
gprof ./a.out

index % time    self  children    called     name
                                                 <spontaneous>
[1]    100.0    0.00    1.79                 main [1]
                1.44    0.00   20000/20000       f2() [2]
                0.35    0.00   10000/10000       f1() [3]
-----------------------------------------------
                1.44    0.00   20000/20000       main [1]
[2]     80.4    1.44    0.00   20000         f2() [2]
-----------------------------------------------
                0.35    0.00   10000/10000       main [1]
[3]     19.6    0.35    0.00   10000         f1() [3]
-----------------------------------------------

有不少GUI工具可以用更加友好的方式显示信息,例如Kprof

使用gcov做代码覆盖率

void f1()
{
    int f = 0;
    f++;
}
void f2()
{
    int f = 0;
    f++;
}

int main(int argc, char** argv) 
{
    if(argc > 1)
    {
        f1();
    }
    else
    {
        f2();
    }
    return 0;                                                                                                                              
}

gcc main.c -fprofile-arcs -ftest-coverage
./a.out
gcov main.c

    -:    0:Source:main.c                                                                                                              
    -:    0:Graph:main.gcno
    -:    0:Data:main.gcda
    -:    0:Runs:1
    -:    0:Programs:1
#####:    1:void f1()
    -:    2:{ 
#####:    3:    int f = 0;
#####:    4:    f++;
#####:    5:} 
    1:    6:void f2()
    -:    7:{ 
    1:    8:    int f = 0;
    1:    9:    f++;
    1:   10:}
    -:   11: 
    1:   12:int main(int argc, char** argv) 
    -:   13:{
    1:   14:    if(argc > 1)
    -:   15:    {   
#####:   16:        f1();
    -:   17:    }   
    -:   18:    else
    -:   19:    {   
    1:   20:        f2();
    -:   21:    }   
    1:   22:    return 0;
    -:   23:}

参考

  1. http://blog.csdn.net/yukin_xue/article/details/7653482
  2. http://www.cnblogs.com/rocketfan/archive/2009/11/15/1603465.html
  3. http://blog.csdn.net/kimsangbaek/article/details/527671