본문 바로가기

Eureka/Coding

[Tip] How to get Execution Time in linux C

자신이 만든 함수나 소스특정 부분의 수행 속도를 구하고 싶을때가 종종 있다.
다음과 같은 방법으로 사용 할 수있다.

1. 필요 헤더(necessary header)

#include <sys/time.h>
#include <unistd.h>


2. 사용할 구조체(will use structure)
해당 부분은 따로 소스에 쓰지 않아도 됩니다.

struct timeval
{
    long tv_sec;       // 초
    long tv_usec;      // 마이크로초
}


3. 사용할 함수(will use function)

// 현재 시간을 얻는 함수
int gettimeofday(struct timeval *tv, struct timezone *tz);

// 시간을 출력하는데 사용할 함수(해당 부분은  소스코드에 정의 하셔야합니다.)
void getElapsedTime(struct timeval Tstart, struct timeval Tend)
{
    Tend.tv_usec = Tend.tv_usec - Tstart.tv_usec;
    Tend.tv_sec  = Tend.tv_sec - Tstart.tv_sec;
    Tend.tv_usec += (Tend.tv_sec*1000000);

    printf("Elapsed Time: %lf sec\n", Tend.tv_usec / 1000000.0);
}


4. 사용법(usage)

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>

void getElapsedTime(struct timeval Tstart, struct timeval Tend)
{
    Tend.tv_usec = Tend.tv_usec - Tstart.tv_usec;
    Tend.tv_sec  = Tend.tv_sec - Tstart.tv_sec;
    Tend.tv_usec += (Tend.tv_sec*1000000);

    printf("Elapsed Time: %lf sec\n", Tend.tv_usec / 1000000.0);
}


int main()
{
    int i = 0;
    int cnt = 0;
    struct timeval Tstart, Tend;

    
gettimeofday(&Tstart, NULL);     // 현재시간 구하기(측정할 소스부분 수행 전에 사용)     for(i = 0; i < 1000000000; i++)
        cnt++;
    gettimeofday(&Tend, NULL); // 현재시간 구하기(측정할 소스부분 수행 후에 사용)
    getElapsedTime(Tstart, Tend); // 정의된 함수로 시간 구하기
    return 1;
}


5. 결과(result)

Elapsed Time: 3.113982 sec