コアダンプの数だけ強くなれるよ

見習いエンジニアの備忘log

コードの処理速度計測にgprofを試してみた

GNUのプロファイラ gprofでコードの処理速度計測を試してみた。
関数単位、LINE(行)単位での実行速度の計測ができる模様。

今回は関数単位でお試し。

使い方は"-pg"のオプションを付与してコンパイルしたバイナリを実行後にgprofコマンドをかませばOK。

gproftest.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define LOOP_BASE_COUNT (100*1000)

void function1(void)
{
    char buf1[1024] = {0};
    char buf2[1024] = {0};

    /* メモリ操作で負荷をかける */
    for(int i = 0; i < LOOP_BASE_COUNT; i++) {
        memset(buf1, 0xff, sizeof(buf1));
        memcpy(buf2, buf1, sizeof(buf2));
    }
}

void function2(void)
{
    char buf1[1024] = {0};
    char buf2[1024] = {0};

    for(int i = 0; i < LOOP_BASE_COUNT*10; i++) {
        memset(buf1, 0xff, sizeof(buf1));
        memcpy(buf2, buf1, sizeof(buf2));
    }
}

void function3(void)
{
    char buf1[1024] = {0};
    char buf2[1024] = {0};

    for(int i = 0; i < LOOP_BASE_COUNT*1000; i++) {
        memset(buf1, 0xff, sizeof(buf1));
        memcpy(buf2, buf1, sizeof(buf2));
    }
}

int main(void)
{
    function1();
    function2();
    function3();

    return 0;
}


Makefile

$ cat Makefile
gproftest: gproftest.c
        gcc -O2 -pg -std=gnu99 -o gproftest gproftest.c


実行例

$ make
gcc -O2 -pg -std=gnu99 -o gproftest gproftest.c
$
$ time ./gproftest

real    0m10.355s
user    0m10.341s
sys     0m0.004s
$
$
$ gprof gproftest gmon.out
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total
 time   seconds   seconds    calls   s/call   s/call  name
 99.88     10.31    10.31        1    10.31    10.31  function3
  0.98     10.41     0.10        1     0.10     0.10  function2
  0.00     10.41     0.00        1     0.00     0.00  function1
...(後略)... 


[その他]
どうやらコンパイル時に -O3 で最適化すると上手くいかないぽい。