Search code examples
c++timelocaltime

measure time difference


I want to measure in milliseconds how much time there is between when I start my application and another time, for example 16:00 o'clock. What is the best way to do this?

I looked around "clock" function but it's not what I need.

Operating system: Win NT and above


Solution

  • Look up gettimeofday for POSIX systems, and timeGetTime for Windows.

    Edit: Seems the OP was asking for code to compare current time/date against another time/date. The following snippet demonstrates how to get current date and time on Windows:

     #include <Windows.h>
     #include <stdio.h>
    
     void main()
     {
         SYSTEMTIME st;
         GetSystemTime(&st);
         printf("Year:%d\nMonth:%d\nDate:%d\nHour:%d\nMin:%d\nSecond:%d\n"
           ,st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond);
     }
    

    And here's how to compute the difference between two SYSTEMTIME objects:

     #include <windows.h>
     #include <iostream>
    
     // Return time difference in units of 100 us.
     _int64 Delta(const SYSTEMTIME st1, const SYSTEMTIME st2) {
      union timeunion {
          FILETIME fileTime;
          ULARGE_INTEGER ul;
      } ;
    
      timeunion ft1;
      timeunion ft2;
    
      SystemTimeToFileTime(&st1, &ft1.fileTime);
      SystemTimeToFileTime(&st2, &ft2.fileTime);
    
      return ft2.ul.QuadPart - ft1.ul.QuadPart;
    }
    
    int main() {
      SYSTEMTIME t1 = {0}, t2 = {0};
      t1.wDay = 10;
      t1.wMonth = 4;
      t1.wYear = 2009;
    
      t2.wDay = 12;
      t2.wMonth = 4;
      t2.wYear = 2009;
    
      _int64 i = Delta(t1, t2);
      std::cout << "times are " << i / 10000000 << " seconds apart\n";
    
      return 0;
    }
    

    Those two samples should give you the tools to do what you need.