开发者

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开发者_JAVA技巧 do this?

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

Operating system: Win NT and above


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.


If you're on a POSIX system, you can use gettimeofday(3):

struct timeval start, end;
gettimeofday(&start, NULL);
...
gettimeofday(&end, NULL);

// Watch out for overflow!
int delta_milliseconds = 1000 * (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)/1000;

If you're on Windows, you can use GetTickCount:

DWORD start, end;
start = GetTickCount();
...
end = GetTickCount();
int delta_milliseconds = end - start;

But but aware that GetTickCount only has a resolution of about 10-16 ms. If you need more precision, use QueryPerformanceCounter and QueryPerformanceFrequency instead:

// Error-checking omitted for expository purposes
LARGE_INTEGER freq, start, end;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
...
QueryPerformanceCounter(&end);
double delta_milliseconds = (double)(end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜