본문 바로가기

Programing Language/C, C++

C언어 프로파일링 gprof#2 - 예제코드

반응형

gprof의 경우에 실행 시간이 너무 작은 경우, 계산이 안되는 것 같기도 합니다.[^1]
[^1]: 정확한 정보는 아닙니다.
다음은 제가 대학원시절 짠 예제코드입니다. 적당히 함수도 있고 해서 사용하기 좋습니다.
2D lattice에서 퍼콜레이션이 일어나는지 확인하는 코드입니다.
L size = 64, Ensemble = 50 인데 실행시간은 대략 10초정도로 gprof결과를 보기 적절한 실행시간으로 조절했습니다.
참고하세요 ^_^

script

g++ 2d_percolation.c mt19937ar.c -pg -o example.out
chmod 755 example.out
gprof example.out > gprof.log

Result

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  ms/call  ms/call  name    
 51.04      1.02     1.02 288629683     0.00     0.00  findroot(int, int*)
 49.04      2.00     0.98       50    19.62    40.03  percolate(int*, int (*) [4], int*, int (*) [4096])
  0.00      2.00     0.00   204800     0.00     0.00  genrand_int32()
  0.00      2.00     0.00   204800     0.00     0.00  genrand_real2()
  0.00      2.00     0.00       50     0.00     0.00  permutation(int*, int (*) [4], int*)
  0.00      2.00     0.00        1     0.00     0.00  boundaries(int*, int (*) [4], int*)
  0.00      2.00     0.00        1     0.00     0.00  init_genrand(unsigned long)

 %         the percentage of the total running time of the
time       program used by this function.

cumulative a running sum of the number of seconds accounted
 seconds   for by this function and those listed above it.

 self      the number of seconds accounted for by this
seconds    function alone.  This is the major sort for this
           listing.

calls      the number of times this function was invoked, if
           this function is profiled, else blank.

 self      the average number of milliseconds spent in this
ms/call    function per call, if this function is profiled,
       else blank.

 total     the average number of milliseconds spent in this
ms/call    function and its descendents per call, if this
       function is profiled, else blank.

name       the name of the function.  This is the minor sort
           for this listing. The index shows the location of
       the function in the gprof listing. If the index is
       in parenthesis it shows where it would appear in
       the gprof listing if it were to be printed.

Copyright (C) 2012-2018 Free Software Foundation, Inc.

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.

             Call graph (explanation follows)


granularity: each sample hit covers 2 byte(s) for 0.50% of 2.00 seconds

index % time    self  children    called     name
                                                 <spontaneous>
[1]    100.0    0.00    2.00                 main [1]
                0.98    1.02      50/50          percolate(int*, int (*) [4], int*, int (*) [4096]) [2]
                0.00    0.00      50/50          permutation(int*, int (*) [4], int*) [12]
                0.00    0.00       1/1           init_genrand(unsigned long) [14]
                0.00    0.00       1/1           boundaries(int*, int (*) [4], int*) [13]
-----------------------------------------------
                0.98    1.02      50/50          main [1]
[2]    100.0    0.98    1.02      50         percolate(int*, int (*) [4], int*, int (*) [4096]) [2]
                1.02    0.00 288629683/288629683     findroot(int, int*) [3]
-----------------------------------------------
                             235814316             findroot(int, int*) [3]
                1.02    0.00 288629683/288629683     percolate(int*, int (*) [4], int*, int (*) [4096]) [2]
[3]     51.0    1.02    0.00 288629683+235814316 findroot(int, int*) [3]
                             235814316             findroot(int, int*) [3]
-----------------------------------------------
                0.00    0.00  204800/204800      genrand_real2() [11]
[10]     0.0    0.00    0.00  204800         genrand_int32() [10]
-----------------------------------------------
                0.00    0.00  204800/204800      permutation(int*, int (*) [4], int*) [12]
[11]     0.0    0.00    0.00  204800         genrand_real2() [11]
                0.00    0.00  204800/204800      genrand_int32() [10]
-----------------------------------------------
                0.00    0.00      50/50          main [1]
[12]     0.0    0.00    0.00      50         permutation(int*, int (*) [4], int*) [12]
                0.00    0.00  204800/204800      genrand_real2() [11]
-----------------------------------------------
                0.00    0.00       1/1           main [1]
[13]     0.0    0.00    0.00       1         boundaries(int*, int (*) [4], int*) [13]
-----------------------------------------------
                0.00    0.00       1/1           main [1]
[14]     0.0    0.00    0.00       1         init_genrand(unsigned long) [14]
-----------------------------------------------

 This table describes the call tree of the program, and was sorted by
 the total amount of time spent in each function and its children.

 Each entry in this table consists of several lines.  The line with the
 index number at the left hand margin lists the current function.
 The lines above it list the functions that called this function,
 and the lines below it list the functions this one called.
 This line lists:
     index    A unique number given to each element of the table.
        Index numbers are sorted numerically.
        The index number is printed next to every function name so
        it is easier to look up where the function is in the table.

     % time    This is the percentage of the `total' time that was spent
        in this function and its children.  Note that due to
        different viewpoints, functions excluded by options, etc,
        these numbers will NOT add up to 100%.

     self    This is the total amount of time spent in this function.

     children    This is the total amount of time propagated into this
        function by its children.

     called    This is the number of times the function was called.
        If the function called itself recursively, the number
        only includes non-recursive calls, and is followed by
        a `+' and the number of recursive calls.

     name    The name of the current function.  The index number is
        printed after it.  If the function is a member of a
        cycle, the cycle number is printed between the
        function's name and the index number.


 For the function's parents, the fields have the following meanings:

     self    This is the amount of time that was propagated directly
        from the function into this parent.

     children    This is the amount of time that was propagated from
        the function's children into this parent.

     called    This is the number of times this parent called the
        function `/' the total number of times the function
        was called.  Recursive calls to the function are not
        included in the number after the `/'.

     name    This is the name of the parent.  The parent's index
        number is printed after it.  If the parent is a
        member of a cycle, the cycle number is printed between
        the name and the index number.

 If the parents of the function cannot be determined, the word
 `<spontaneous>' is printed in the `name' field, and all the other
 fields are blank.

 For the function's children, the fields have the following meanings:

     self    This is the amount of time that was propagated directly
        from the child into the function.

     children    This is the amount of time that was propagated from the
        child's children to the function.

     called    This is the number of times the function called
        this child `/' the total number of times the child
        was called.  Recursive calls by the child are not
        listed in the number after the `/'.

     name    This is the name of the child.  The child's index
        number is printed after it.  If the child is a
        member of a cycle, the cycle number is printed
        between the name and the index number.

 If there are any cycles (circles) in the call graph, there is an
 entry for the cycle-as-a-whole.  This entry shows who called the
 cycle (as parents) and the members of the cycle (as children.)
 The `+' recursive calls entry shows the number of function calls that
 were internal to the cycle, and the calls entry for each member shows,
 for that member, how many times it was called from other members of
 the cycle.

Copyright (C) 2012-2018 Free Software Foundation, Inc.

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved.

Index by function name

  [13] boundaries(int*, int (*) [4], int*) [10] genrand_int32() [2] percolate(int*, int (*) [4], int*, int (*) [4096])
  [12] permutation(int*, int (*) [4], int*) [11] genrand_real2()
  [14] init_genrand(unsigned long) [3] findroot(int, int*)

2d_percolation.c

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

#define L 64
#define N (L*L)
#define EMPTY -N-1
#define ENS 50

void init_genrand(unsigned long);
double genrand_real2(void);

void boundaries(int ptr[],int nn[][4], int order[]);
void permutation(int ptr[],int nn[][4], int order[]);
void percolate(int ptr[],int nn[][4], int order[],int pp[][N]);
int findroot(int i,int ptr[]);

int main(void){
    int ptr[N];    // Array of pointer (group seed or state)
    int nn[N][4];    // Nearest Neighbor
    int order[N];    // Occupation order
    int pp[4][N];
    init_genrand(time(NULL));

    for(int i=0;i<N;i++) pp[0][i]=pp[1][i]=pp[2][i]=pp[3][i]=0;
    boundaries(ptr,nn,order);

    for(int e=0;e<ENS;e++){
        permutation(ptr,nn,order);
        percolate(ptr,nn,order,pp);
    }

    for(int i=0;i<N;i++){
        printf("%d\t%f\t",i,i*1.0/N);
        for(int j=0; j<4; j++)    printf("%f\t",pp[j][i]*1./ENS);
        printf("\n");
    }

    /*
    for(int i=0;i<L;i++){
        for(int j=0;j<L;j++)    printf(" %5d",ptr[L*i+j]);
        printf("\n");}*/

    return 0;
}

void boundaries(int ptr[],int nn[][4], int order[]){
    for(int i=0; i<N; i++){
        nn[i][0]=(i+1)%N;    //right
        nn[i][1]=(i+N-1)%N;    //left
        nn[i][2]=(i+L)%N;    //down
        nn[i][3]=(i+N-L)%N;    //up
        if (i%L==0) nn[i][1]=i+L-1;    // i is end of left
        if ((i+1)%L==0) nn[i][0]=i-L+1;    // i is end of rignt
}}
void permutation(int ptr[],int nn[][4], int order[]){    // occupy process
    int i,j;
    int temp;
    for(i=0;i<N;i++) order[i]=i;
    for(i=0;i<N;i++){
        j=i+(N-i)*genrand_real2();
        temp=order[i];
        order[i]=order[j];
        order[j]=temp;
    }
}
void percolate(int ptr[],int nn[][4], int order[],int pp[][N]){
    int i,j;
    int s1,s2;
    int r1,r2;
    int big=0;
    for(i=0;i<N;i++) ptr[i] = EMPTY ;
    for(i=0;i<N;i++){
        r1 = s1 = order[i];
        ptr[s1] = -1;
        for(j=0;j<4;j++){
            s2 = nn[s1][j];
            if(ptr[s2] != EMPTY ){
                r2 = findroot(s2,ptr);
                if(r2!=r1){
                    if(ptr[r1]>ptr[r2]){
                        ptr[r2] += ptr[r1];
                        ptr[r1] = r2;
                        r1 = r2;
                    }
                    else{
                        ptr[r1] += ptr[r2];
                        ptr[r2] = r1;
                    }
                    if(-ptr[r1]>big) big = -ptr[r1];
        }}}
        //printf("%i\t%i\n",i+1,big);
        int vp,hp;

        for(j=0;j<N;j+=L){//horizontal percolation
            if(ptr[j]!=EMPTY){
                int temp;
                temp = findroot(j,ptr);
                hp=1;
                int k=hp;
                while(k==hp){
                    for(k=hp;k<N;k+=L){
                        int temp2;
                        if(ptr[k]!=EMPTY){
                            temp2 = findroot(k,ptr);
                            if(temp==temp2)    k=2*N;
                    }}
                    if(k==(2*N+L)){
                        hp++;
                        k=hp;
                    }
                    if(hp==L){
                        hp=-1;
                        j=N;
        }}}}
        for(j=0;j<L;j++){//vertical percolation
            if(ptr[j]!=EMPTY){
                int temp;
                temp = findroot(j,ptr);
                vp=1;
                int k=vp;
                while(k==vp){
                    for(k=vp*L;k<(vp+1)*L;k++){
                        int temp2;
                        if(ptr[k]!=EMPTY){
                            temp2 = findroot(k,ptr);
                            if(temp==temp2)    k=2*N;
                    }}
                    if(k==(2*N+1)){
                        vp++;
                        k=vp;
                    }
                    if(vp==L){
                        vp=-1;
                        j=L;
        }}}}
/*        for(int o=0;o<L;o++){
                for(int u=0;u<L;u++)    printf(" %5d",ptr[L*o+u]);
                printf("\n");}
printf("%d and %d\n",vp,hp);*/
        //dktif(vp!=-1) vp=0;
        //if(hp!=-1) hp=0;
        //if(vp+hp==-2)    pp[2][i]++;
        //if(vp==-1)    pp[0][i]++;
        if(vp+hp<0)    pp[1][i]++;
        //if(vp+hp==-1)    pp[3][i]++;
}}
int findroot(int i,int ptr[]){
    if (ptr[i]<0) return i;
    return ptr[i] = findroot(ptr[i],ptr);
}

mt19937ar.c

/* 
   A C-program for MT19937, with initialization improved 2002/1/26.
   Coded by Takuji Nishimura and Makoto Matsumoto.

   Before using, initialize the state by using init_genrand(seed)  
   or init_by_array(init_key, key_length).

   Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura,
   All rights reserved.                          

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     1. Redistributions of source code must retain the above copyright
        notice, this list of conditions and the following disclaimer.

     2. Redistributions in binary form must reproduce the above copyright
        notice, this list of conditions and the following disclaimer in the
        documentation and/or other materials provided with the distribution.

     3. The names of its contributors may not be used to endorse or promote 
        products derived from this software without specific prior written 
        permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
   A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


   Any feedback is very welcome.
   http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html
   email: m-mat @ math.sci.hiroshima-u.ac.jp (remove space)
*/

#include <stdio.h>

/* Period parameters */  
#define N 624
#define M 397
#define MATRIX_A 0x9908b0dfUL   /* constant vector a */
#define UPPER_MASK 0x80000000UL /* most significant w-r bits */
#define LOWER_MASK 0x7fffffffUL /* least significant r bits */

static unsigned long mt[N]; /* the array for the state vector  */
static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */

/* initializes mt[N] with a seed */
void init_genrand(unsigned long s)
{
    mt[0]= s & 0xffffffffUL;
    for (mti=1; mti<N; mti++) {
        mt[mti] = 
        (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); 
        /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */
        /* In the previous versions, MSBs of the seed affect   */
        /* only MSBs of the array mt[].                        */
        /* 2002/01/09 modified by Makoto Matsumoto             */
        mt[mti] &= 0xffffffffUL;
        /* for >32 bit machines */
    }
}

/* initialize by an array with array-length */
/* init_key is the array for initializing keys */
/* key_length is its length */
/* slight change for C++, 2004/2/26 */
void init_by_array(unsigned long init_key[], int key_length)
{
    int i, j, k;
    init_genrand(19650218UL);
    i=1; j=0;
    k = (N>key_length ? N : key_length);
    for (; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL))
          + init_key[j] + j; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++; j++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
        if (j>=key_length) j=0;
    }
    for (k=N-1; k; k--) {
        mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL))
          - i; /* non linear */
        mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */
        i++;
        if (i>=N) { mt[0] = mt[N-1]; i=1; }
    }

    mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ 
}

/* generates a random number on [0,0xffffffff]-interval */
unsigned long genrand_int32(void)
{
    unsigned long y;
    static unsigned long mag01[2]={0x0UL, MATRIX_A};
    /* mag01[x] = x * MATRIX_A  for x=0,1 */

    if (mti >= N) { /* generate N words at one time */
        int kk;

        if (mti == N+1)   /* if init_genrand() has not been called, */
            init_genrand(5489UL); /* a default initial seed is used */

        for (kk=0;kk<N-M;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        for (;kk<N-1;kk++) {
            y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK);
            mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL];
        }
        y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK);
        mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL];

        mti = 0;
    }

    y = mt[mti++];

    /* Tempering */
    y ^= (y >> 11);
    y ^= (y << 7) & 0x9d2c5680UL;
    y ^= (y << 15) & 0xefc60000UL;
    y ^= (y >> 18);

    return y;
}

/* generates a random number on [0,0x7fffffff]-interval */
long genrand_int31(void)
{
    return (long)(genrand_int32()>>1);
}

/* generates a random number on [0,1]-real-interval */
double genrand_real1(void)
{
    return genrand_int32()*(1.0/4294967295.0); 
    /* divided by 2^32-1 */ 
}

/* generates a random number on [0,1)-real-interval */
double genrand_real2(void)
{
    return genrand_int32()*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on (0,1)-real-interval */
double genrand_real3(void)
{
    return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); 
    /* divided by 2^32 */
}

/* generates a random number on [0,1) with 53-bit resolution*/
double genrand_res53(void) 
{ 
    unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; 
    return(a*67108864.0+b)*(1.0/9007199254740992.0); 
} 
/* These real versions are due to Isaku Wada, 2002/01/09 added */
/*
int main(void)
{
    int i;
    unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4;
    init_by_array(init, length);
    printf("1000 outputs of genrand_int32()\n");
    for (i=0; i<1000; i++) {
      printf("%10lu ", genrand_int32());
      if (i%5==4) printf("\n");
    }
    printf("\n1000 outputs of genrand_real2()\n");
    for (i=0; i<1000; i++) {
      printf("%10.8f ", genrand_real2());
      if (i%5==4) printf("\n");
    }
    return 0;
}
*/
반응형

'Programing Language > C, C++' 카테고리의 다른 글

C언어 프로파일하기, gcc profiler gprof  (6) 2017.03.30