IT

C 프로그램의 실행 시간

lottoking 2020. 5. 12. 08:13
반응형

C 프로그램의 실행 시간


여러 프로세서에서 병렬로 실행하려는 C 프로그램이 있습니다. 실행 시간을 기록 할 수 있어야합니다 (1 초에서 몇 분까지 가능). 나는 답을 찾았지만 모두 clock()함수를 사용하도록 제안하는 것처럼 보 였으며 프로그램에 걸린 시계 수를 Clocks_per_second으로 나눈 값을 계산해야 합니다.

Clocks_per_second값이 어떻게 계산 되는지 잘 모르겠습니다 .

Java에서는 실행 전후에 현재 시간을 밀리 초 단위로 사용합니다.

C에도 비슷한 것이 있습니까? 나는 보았지만 두 번째 해상도보다 더 나은 것을 얻는 방법을 찾지 못하는 것 같습니다.

또한 프로파일 러가 옵션 일 것임을 알고 있지만 타이머를 직접 구현하려고합니다.

감사


CLOCKS_PER_SEC에 선언 된 상수입니다 <time.h>. C 응용 프로그램 내에서 작업에 사용 된 CPU 시간을 얻으려면 다음을 사용하십시오.

clock_t begin = clock();

/* here, do your time-consuming job */

clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;

이것은 시간을 부동 소수점 유형으로 반환합니다. 이것은 1 초보다 정확할 수 있습니다 (예 : 4.52 초 측정). 정밀도는 아키텍처에 따라 다릅니다. 최신 시스템에서는 쉽게 10ms 이하를 얻을 수 있지만 구형 Windows 시스템 (Win98 시대)에서는 60ms에 가깝습니다.

clock()표준 C이고; "모든 곳에서"작동합니다. getrusage()유닉스 계열 시스템과 같은 시스템 별 기능이 있습니다.

Java System.currentTimeMillis()는 동일한 것을 측정하지 않습니다. "벽시계": 프로그램을 실행하는 데 걸리는 시간을 측정하는 데 도움이되지만 사용 된 CPU 시간을 알려주지는 않습니다. 멀티 태스킹 시스템 (즉, 모든 시스템)에서 이러한 시스템은 크게 다를 수 있습니다.


Unix 쉘을 사용하여 실행중인 경우 time 명령을 사용할 수 있습니다.

하기

$ time ./a.out

실행 파일로 a.out을 가정하면이를 실행하는 데 걸리는 시간이 주어집니다.


당신은 기능적으로 이것을 원합니다 :

#include <sys/time.h>

struct timeval  tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);

printf ("Total time = %f seconds\n",
         (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
         (double) (tv2.tv_sec - tv1.tv_sec));

이것은 초가 아니라 마이크로 초 단위로 측정됩니다.


일반 바닐라 C에서 :

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

int main()
{
    clock_t tic = clock();

    my_expensive_function_which_can_spawn_threads();

    clock_t toc = clock();

    printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);

    return 0;
}

간단한 프로그램의 대부분은 계산 시간이 밀리 초입니다. 그래서, 당신은 이것이 유용하다고 생각합니다.

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

int main(){
    clock_t start = clock();
    // Execuatable code
    clock_t stop = clock();
    double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
    printf("Time elapsed in ms: %f", elapsed);
}

전체 프로그램의 런타임을 계산하고 Unix 시스템에있는 경우 다음 과 같이 time 명령을 사용하여 프로그램을 실행하십시오.time ./a.out


답변의 많은 제안 된 clock()다음과 CLOCKS_PER_SEC에서 time.h. 이것은 내 /bits/time.h파일이 말하는 것이므로 아마도 나쁜 생각입니다 .

/* ISO/IEC 9899:1990 7.12.1: <time.h>
The macro `CLOCKS_PER_SEC' is the number per second of the value
returned by the `clock' function. */
/* CAE XSH, Issue 4, Version 2: <time.h>
The value of CLOCKS_PER_SEC is required to be 1 million on all
XSI-conformant systems. */
#  define CLOCKS_PER_SEC  1000000l

#  if !defined __STRICT_ANSI__ && !defined __USE_XOPEN2K
/* Even though CLOCKS_PER_SEC has such a strange value CLK_TCK
presents the real value for clock ticks per second for the system.  */
#   include <bits/types.h>
extern long int __sysconf (int);
#   define CLK_TCK ((__clock_t) __sysconf (2))  /* 2 is _SC_CLK_TCK */
#  endif

따라서 CLOCKS_PER_SEC컴파일하는 데 사용하는 옵션에 따라 1000000으로 정의 될 수 있으므로 좋은 솔루션처럼 보이지 않습니다.


매크로로 Thomas Pornin의 답변 :

#define TICK(X) clock_t X = clock()
#define TOCK(X) printf("time %s: %g sec.\n", (#X), (double)(clock() - (X)) / CLOCKS_PER_SEC)

다음과 같이 사용하십시오.

TICK(TIME_A);
functionA();
TOCK(TIME_A);

TICK(TIME_B);
functionB();
TOCK(TIME_B);

산출:

time TIME_A: 0.001652 sec.
time TIME_B: 0.004028 sec.

프로그램을 실행하는 데 걸리는 시간 을 측정 하는 것은 기계가 특정 순간에 가하는 부하에 따라 달라진다는 점을 고려해야합니다 .

C로 현재 시간을 얻는 방법은 여러 가지 방법으로 달성 할 수 있다는 것을 알면 더 쉬운 방법입니다.

#include <time.h>

#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
  ruse.ru_stime.tv_sec + 1e-6 * \
  (ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))

int main(void) {
    time_t start, end;
    double first, second;

    // Save user and CPU start time
    time(&start);
    first = CPU_TIME;

    // Perform operations
    ...

    // Save end time
    time(&end);
    second = CPU_TIME;

    printf("cpu  : %.2f secs\n", second - first); 
    printf("user : %d secs\n", (int)(end - start));
}

도움이 되길 바랍니다.

문안 인사!


ANSI C는 두 번째 정밀 시간 함수 만 지정합니다. 그러나 POSIX 환경에서 실행중인 경우 , UNIX Epoch 이후에 경과 된 시간의 마이크로 초 해상도를 제공 하는 gettimeofday () 함수를 사용할 수 있습니다 .

As a side note, I wouldn't recommend using clock() since it is badly implemented on many(if not all?) systems and not accurate, besides the fact that it only refers to how long your program has spent on the CPU and not the total lifetime of the program, which according to your question is what I assume you would like to measure.


(All answers here are lacking, if your sysadmin changes the systemtime, or your timezone has differing winter- and sommer-times. Therefore...)

On linux use: clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable); It's not affected if the system-admin changes the time, or you live in a country with winter-time different from summer-time, etc.

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

#include <unistd.h> /* for sleep() */

int main() {
    struct timespec begin, end;
    clock_gettime(CLOCK_MONOTONIC_RAW, &begin);

    sleep(1);      // waste some time

    clock_gettime(CLOCK_MONOTONIC_RAW, &end);

    printf ("Total time = %f seconds\n",
            (end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
            (end.tv_sec  - begin.tv_sec));

}

man clock_gettime states:

CLOCK_MONOTONIC
              Clock  that  cannot  be set and represents monotonic time since some unspecified starting point.  This clock is not affected by discontinuous jumps in the system time
              (e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.

Every solution's are not working in my system.

I can get using

#include <time.h>

double difftime(time_t time1, time_t time0);

    #include<time.h>
    #include<stdio.h>
    int main(){
clock_t begin=clock();

    int i;
for(i=0;i<100000;i++){
printf("%d",i);

}
clock_t end=clock();
printf("Time taken:%lf",(double)(end-begin)/CLOCKS_PER_SEC);
}

This program will work like charm.


I've found that the usual clock(), everyone recommends here, for some reason deviates wildly from run to run, even for static code without any side effects, like drawing to screen or reading files. It could be because CPU changes power consumption modes, OS giving different priorities, etc...

So the only way to reliably get the same result every time with clock() is to run the measured code in a loop multiple times (for several minutes), taking precautions to prevent the compiler from optimizing it out: modern compilers can precompute the code without side effects running in a loop, and move it out of the loop., like i.e. using random input for each iteration.

After enough samples are collected into an array, one sorts that array, and takes the middle element, called median. Median is better than average, because it throws away extreme deviations, like say antivirus taking up all CPU up or OS doing some update.

Here is a simple utility to measure execution performance of C/C++ code, averaging the values near median: https://github.com/saniv/gauge

I'm myself still looking for a more robust and faster way to measure code. One could probably try running the code in controlled conditions on bare metal without any OS, but that will give unrealistic result, because in reality OS does get involved.

x86 has these hardware performance counters, which including the actual number of instructions executed, but they are tricky to access without OS help, hard to interpret and have their own issues ( http://archive.gamedev.net/archive/reference/articles/article213.html ). Still they could be helpful investigating the nature of the bottle neck (data access or actual computations on that data).


Some might find a different kind of input useful: I was given this method of measuring time as part of a university course on GPGPU-programming with NVidia CUDA (course description). It combines methods seen in earlier posts, and I simply post it because the requirements give it credibility:

unsigned long int elapsed;
struct timeval t_start, t_end, t_diff;
gettimeofday(&t_start, NULL);

// perform computations ...

gettimeofday(&t_end, NULL);
timeval_subtract(&t_diff, &t_end, &t_start);
elapsed = (t_diff.tv_sec*1e6 + t_diff.tv_usec);
printf("GPU version runs in: %lu microsecs\n", elapsed);

I suppose you could multiply with e.g. 1.0 / 1000.0 to get the unit of measurement that suits your needs.


Comparison of execution time of bubble sort and selection sort I have a program which compares the execution time of bubble sort and selection sort. To find out the time of execution of a block of code compute the time before and after the block by

 clock_t start=clock();
 clock_t end=clock();
 CLOCKS_PER_SEC is constant in time.h library

Example code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
   int a[10000],i,j,min,temp;
   for(i=0;i<10000;i++)
   {
      a[i]=rand()%10000;
   }
   //The bubble Sort
   clock_t start,end;
   start=clock();
   for(i=0;i<10000;i++)
   {
     for(j=i+1;j<10000;j++)
     {
       if(a[i]>a[j])
       {
         int temp=a[i];
         a[i]=a[j];
         a[j]=temp;
       }
     }
   }
   end=clock();
   double extime=(double) (end-start)/CLOCKS_PER_SEC;
   printf("\n\tExecution time for the bubble sort is %f seconds\n ",extime);

   for(i=0;i<10000;i++)
   {
     a[i]=rand()%10000;
   }
   clock_t start1,end1;
   start1=clock();
   // The Selection Sort
   for(i=0;i<10000;i++)
   {
     min=i;
     for(j=i+1;j<10000;j++)
     {
       if(a[min]>a[j])
       {
         min=j;
       }
     }
     temp=a[min];
     a[min]=a[i];
     a[i]=temp;
   }
   end1=clock();
   double extime1=(double) (end1-start1)/CLOCKS_PER_SEC;
   printf("\n");
   printf("\tExecution time for the selection sort is %f seconds\n\n", extime1);
   if(extime1<extime)
     printf("\tSelection sort is faster than Bubble sort by %f seconds\n\n", extime - extime1);
   else if(extime1>extime)
     printf("\tBubble sort is faster than Selection sort by %f seconds\n\n", extime1 - extime);
   else
     printf("\tBoth algorithms have the same execution time\n\n");
}

참고URL : https://stackoverflow.com/questions/5248915/execution-time-of-c-program

반응형