2014-03-25 1 views
0

MAIN.C :위해 clock_gettime

int sum() 
{ 
    int x = 100, y =200, z; 
    z =x; 
    z=y; 
    printf("value is %d", z); 
    return 1; 

} 

int main() 
{ 
    double starttime, stoptime; 
    int a=1, b=10, c; 
    starttime = GetTimeStamp();   // I am calculating time here. 
    printf("start time is %f", starttime); 
    c =a; 
    printf("value is %d", c); 
    c =b; 
    printf("value is %d", c); 
    c= a+b; 

     printf("value is %d", c); 
     printf("value is %d", c); 
     printf("value is %d", c); 
     printf("value is %d", c);  

    stoptime =GetTimeStamp(); // I want to know the time here. 
    printf("stop time is %f", stoptime); 
    return 0; 

} 

타이머 .c :

#define BILLION 1000000L 
typedef unsigned int uint32_t; 

int GetTimeStamp() 
{ 
struct timespec start; 

//double startTime; 

      // if((startTime = clock_gettime(CLOCK_REALTIME, &start)) == -1) 
      if((clock_gettime(CLOCK_REALTIME, &start)) == -1) 
      { 
       perror("clock gettime"); 

      } 
     // startTime =start.tv_sec + 0.0000001 * start.tv_nsec; // to make it milli 


     return ((start.tv_sec + 0.0000001 * start.tv_nsec)/(double)BILLION); 
} 

timer.h :

#ifndef TIMESTAMP_H_ 
#define TIMESTAMP_H_ 
int GetTimeStamp(); 

#endif /* TIMESTAMP_H_ */ 

내가 무료 실행 타이머를 만들려하고 원하는 실행을 시작할 시간과 실행을 마치는 시간을 얻으십시오. 그래서 TIMER.c에서 위의 타이머를 만들었고 main.c에서 사용하고 있습니다. 나는 프로그램 구걸시 MAIN.c에서 GetTimeStamp()를 호출하고 있습니다. 출력 : 시작 시간과 종료 시간이 모두 같은 시간으로 표시됩니다. 1594.0000000

+1

GetTimeStamp 함수의 반환 유형을 확인하고자 할 수 있습니다. 너에게 –

답변

0

tv_nsec에 대한 배율이 잘못되어 일정한 BILLION도 잘못되었습니다. 접두사 n (나노)은 10^-9를 의미하고 10 억은 10^9와 같습니다. 변경 :

return 1e9 * start.tv_sec + start.tv_nsec;  // return ns time stamp 

나 :

return ((start.tv_sec + 0.0000001 * start.tv_nsec)/(double)BILLION); 

return 1e6 * start.tv_sec + start.tv_nsec * 1e-3; // return µs time stamp 

나 :

return 1e3 * start.tv_sec + start.tv_nsec * 1e-6; // return ms time stamp 

나 :

return start.tv_sec + start.tv_nsec * 1e-9;  // return seconds time stamp 

타임 스탬프에 사용하려는 단위에 따라 다릅니다.

이미 다른 곳에서 지적했듯이 예를 들어 int 대신 타임 스탬프가 double인데 이는 더 나은 범위와 해상도를 제공하며 이미 main에서 사용하고 있기 때문입니다.

double GetTimeStamp(void) 
{ 
    ... 

    return 1e9 * start.tv_sec + start.tv_nsec;  // return ns time stamp 
} 
+0

백만을 주셔서 감사합니다. – user3458454

+0

실시간 리눅스에서 동일한 작업을 수행한다면 동일한 API를 사용할 수 있습니까 ?? – user3458454

+0

물론'clock_gettime'은 꽤 표준 적입니다. (a) 모든 플랫폼에서 모든 클럭 유형이 지원되는 것은 아니며 (b) 일부 클럭 유형은 CPU 시간과 일부 벽시계 시간을 반환합니다. 많이 예를 들어 스레드를 사용하고 있다면. –

관련 문제