programing

리눅스에서 C의 밀리초와 나노초의 정확도 차이를 어떻게 출력합니까?

javamemo 2023. 9. 2. 07:55
반응형

리눅스에서 C의 밀리초와 나노초의 정확도 차이를 어떻게 출력합니까?

나는 두 개의 다른 인스턴스 사이의 시간 차이를 출력하는 이 프로그램을 가지고 있지만, 몇 초 안에 정확하게 출력됩니다.밀리초 단위로 출력하고 나노초 단위로 출력하고 싶습니다.

//Prints in accuracy of seconds

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

int main(void)
{
    time_t now, later;
    double seconds;

    time(&now);
    sleep(2);

    time(&later);
    seconds = difftime(later, now);

    printf("%.f seconds difference", seconds);
}

어떻게 하면 그것을 달성할 수 있을까요?

시간(7) 맨 페이지를 먼저 읽습니다.

그런 다음 clock_gettime(2) syscall을 사용할 수 있습니다(링크가 필요할 수 있음).-lrt그것을 얻기 위해).

그래서 당신은 시도할 수 있습니다.

    struct timespec tstart={0,0}, tend={0,0};
    clock_gettime(CLOCK_MONOTONIC, &tstart);
    some_long_computation();
    clock_gettime(CLOCK_MONOTONIC, &tend);
    printf("some_long_computation took about %.5f seconds\n",
           ((double)tend.tv_sec + 1.0e-9*tend.tv_nsec) - 
           ((double)tstart.tv_sec + 1.0e-9*tstart.tv_nsec));

하드웨어 타이머가 나노초의 정확도를 가질 것으로 기대하지 마십시오. 나노초의 해상도를 제공하더라도 마찬가지입니다.또한 몇 밀리초 미만의 시간을 측정하려고 하지 마십시오. 하드웨어가 충분히 충실하지 않습니다.사용할 수도 있습니다.clock_getres일부 클럭의 해상도를 쿼리합니다.

timespec_getC11부터

이 함수는 구현 해상도로 반올림된 최대 나노초까지 반환됩니다.

예: http://en.cppreference.com/w/c/chrono/timespec_get :

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

int main(void)
{
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    char buff[100];
    strftime(buff, sizeof buff, "%D %T", gmtime(&ts.tv_sec));
    printf("Current time: %s.%09ld UTC\n", buff, ts.tv_nsec);
}

출력:

Current time: 02/18/15 14:34:03.048508855 UTC

자세한 내용은 여기에서 확인하십시오. https://stackoverflow.com/a/36095407/895245

여기 그것을 다루는 간단한 매크로가 있습니다.

#include <time.h>
#define CHECK_TIME(x) {\
    struct timespec start,end;\
    clock_gettime(CLOCK_REALTIME, &start);\
    x;\
    clock_gettime(CLOCK_REALTIME, &end);\
    double f = ((double)end.tv_sec*1e9 + end.tv_nsec) - ((double)start.tv_sec*1e9 + start.tv_nsec); \
    printf("time %f ms\n",f/1000000); \
    }

사용 방법은 다음과 같습니다.

CHECK_TIME(foo(a,b,c))

언급URL : https://stackoverflow.com/questions/16275444/how-to-print-time-difference-in-accuracy-of-milliseconds-and-nanoseconds-from-c

반응형