Calculating elapsed time in a C program in milliseconds

后端 未结 5 1215
你的背包
你的背包 2020-11-29 03:36

I want to calculate the time in milliseconds taken by the execution of some part of my program. I\'ve been looking online, but there\'s not much info on this topic. Any of y

相关标签:
5条回答
  • 2020-11-29 03:57

    The gettimeofday function returns the time with microsecond precision (if the platform can support that, of course):

    The gettimeofday() function shall obtain the current time, expressed as seconds and microseconds since the Epoch, and store it in the timeval structure pointed to by tp. The resolution of the system clock is unspecified.

    0 讨论(0)
  • 2020-11-29 04:00

    On Windows, you can just do this:

    DWORD dwTickCount = GetTickCount();
    
    // Perform some things.
    
    printf("Code took: %dms\n", GetTickCount() - dwTickCount);
    

    Not the most general/elegant solution, but nice and quick when you need it.

    0 讨论(0)
  • 2020-11-29 04:07

    C libraries have a function to let you get the system time. You can calculate elapsed time after you capture the start and stop times.

    The function is called gettimeofday() and you can look at the man page to find out what to include and how to use it.

    0 讨论(0)
  • 2020-11-29 04:17

    Best way to answer is with an example:

    #include <sys/time.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    
    /* Return 1 if the difference is negative, otherwise 0.  */
    int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
    {
        long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
        result->tv_sec = diff / 1000000;
        result->tv_usec = diff % 1000000;
    
        return (diff<0);
    }
    
    void timeval_print(struct timeval *tv)
    {
        char buffer[30];
        time_t curtime;
    
        printf("%ld.%06ld", tv->tv_sec, tv->tv_usec);
        curtime = tv->tv_sec;
        strftime(buffer, 30, "%m-%d-%Y  %T", localtime(&curtime));
        printf(" = %s.%06ld\n", buffer, tv->tv_usec);
    }
    
    int main()
    {
        struct timeval tvBegin, tvEnd, tvDiff;
    
        // begin
        gettimeofday(&tvBegin, NULL);
        timeval_print(&tvBegin);
    
        // lengthy operation
        int i,j;
        for(i=0;i<999999L;++i) {
            j=sqrt(i);
        }
    
        //end
        gettimeofday(&tvEnd, NULL);
        timeval_print(&tvEnd);
    
        // diff
        timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
        printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-29 04:21

    Another option ( at least on some UNIX ) is clock_gettime and related functions. These allow access to various realtime clocks and you can select one of the higher resolution ones and throw away the resolution you don't need.

    0 讨论(0)
提交回复
热议问题