How can I get the execution time of a program in milliseconds in C?

后端 未结 6 1044
清酒与你
清酒与你 2020-12-30 09:28

Currently I\'m getting the execution wall time of my program in seconds by calling:

time_t startTime = time(NULL);
//section of code
time_t         


        
6条回答
  •  我在风中等你
    2020-12-30 10:12

    I recently wrote a blog post that explains how to obtain the time in milliseconds cross-platform.

    It will work like time(NULL), but will return the number of milliseconds instead of seconds from the unix epoch on both windows and linux.

    Here is the code

    #ifdef WIN32
    #include 
    #else
    #include 
    #include 
    #endif
    
    /* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
     * windows and linux. */
    
    int64 GetTimeMs64()
    {
    #ifdef WIN32
     /* Windows */
     FILETIME ft;
     LARGE_INTEGER li;
     uint64 ret;
    
     /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
      * to a LARGE_INTEGER structure. */
     GetSystemTimeAsFileTime(&ft);
     li.LowPart = ft.dwLowDateTime;
     li.HighPart = ft.dwHighDateTime;
    
     ret = li.QuadPart;
     ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
     ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */
    
     return ret;
    #else
     /* Linux */
     struct timeval tv;
     uint64 ret;
    
     gettimeofday(&tv, NULL);
    
     ret = tv.tv_usec;
     /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
     ret /= 1000;
    
     /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
     ret += (tv.tv_sec * 1000);
    
     return ret;
    #endif
    }
    

    You can modify it to return microseconds instead of milliesconds if you want.

提交回复
热议问题