C/C++ 에서 clock() 함수를 이용하여 수행시간 측정하기에는 여러가지 방법이 있겠지만

본인이 가장 선호하고, 가장 간편한 방법을 소개한다.


자료구조 전공시간에 전공 도서에서 함수의 수행 시간 측정하는 코드를 처음 접하였다.

(아마도 호로비치 자료구조 책일듯?)


boolean operation을 수행하는 두 라이브러리의 속도를 비교하기 위해서 수행시간 측정을 하게 되었다. 



먼저 clock 함수에 대해 알아보자. 

아래는 C++ 레퍼런스 사이트에서 가져온 내용이다. (링크 참고 : http://www.cplusplus.com/reference/ctime/clock/ )


function

<ctime>

clock

clock_t clock (void);
Clock program
Returns the processor time consumed by the program.

The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second).

The epoch used as reference by clock varies between systems, but it is related to the program execution (generally its launch). To calculate the actual processing time of a program, the value returned by clock shall be compared to a value returned by a previous call to the same function.

Parameters

none

Return Value

The number of clock ticks elapsed since an epoch related to the particular program execution.

On failure, the function returns a value of -1.

clock_t is a type defined in <ctime> as an alias of a fundamental arithmetic type.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* clock example: frequency of primes */
#include <stdio.h>      /* printf */
#include <time.h>       /* clock_t, clock, CLOCKS_PER_SEC */
#include <math.h>       /* sqrt */

int frequency_of_primes (int n) {
  int i,j;
  int freq=n-1;
  for (i=2; i<=n; ++i) for (j=sqrt(i);j>1;--j) if (i%j==0) {--freq; break;}
  return freq;
}

int main ()
{
  clock_t t;
  int f;
  t = clock();
  printf ("Calculating...\n");
  f = frequency_of_primes (99999);
  printf ("The number of primes lower than 100,000 is: %d\n",f);
  t = clock() - t;
  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
  return 0;
}


Output:

Calculating...
The number of primes lower than 100,000 is: 9592
It took me 143 clicks (0.143000 seconds).




간략히 정리해보면, clock 함수는 time.h(c++에서는 ctime) 헤더 파일에 들어있다.


clock_t clock(void); 의 형태로 선언되어 있으며, 그 내부가 궁금한 분은 직접 찾아보기 바란다.

(참고로 Visual studio에서 F12키를 통해 내부 선언으로 찾아갈 수 있다.)


여기서 반환형인 clock_t는 


typedef long clock_t; 


와 같이 선언되어 있는데, 그냥 long이라고 생각하면 된다.


사용법은 위의 예제와 같다. 

측정시작한는 부분에 clock()을 변수에 저장한 뒤, 끝날 때 시간을 빼고 CLOCKS_PER_SEC으로 나눠주면 된다.

즉,

  t = clock();   // 측정 시작
  /* 측정할 함수,코드가 들어갈 자리 */

  t = clock() - t;
  printf ("It took me %d clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);


와 같이 사용하면 된다.






+ Recent posts