14

I want to get difference between two SYSTEMTIME variable. I saw someone asked this question here before, but he was told to convert both SYSTEMTIME structures to FILETIME.. Is there another way to get the difference?

SYSTEMTIME st;
GetSystemTime(&st);

---some code here---

  SYSTEMTIME st2;
  GetSystemTime(&st2);

st-st2?

Mercy
  • 1,862
  • 9
  • 39
  • 75
kakush
  • 3,334
  • 14
  • 47
  • 68

3 Answers3

21
SYSTEMTIME operator-(const SYSTEMTIME& pSr,const SYSTEMTIME& pSl)
{
    SYSTEMTIME t_res;
    FILETIME v_ftime;
    ULARGE_INTEGER v_ui;
    __int64 v_right,v_left,v_res;
    SystemTimeToFileTime(&pSr,&v_ftime);
    v_ui.LowPart=v_ftime.dwLowDateTime;
    v_ui.HighPart=v_ftime.dwHighDateTime;
    v_right=v_ui.QuadPart;

    SystemTimeToFileTime(&pSl,&v_ftime);
    v_ui.LowPart=v_ftime.dwLowDateTime;
    v_ui.HighPart=v_ftime.dwHighDateTime;
    v_left=v_ui.QuadPart;

    v_res=v_right-v_left;

    v_ui.QuadPart=v_res;
    v_ftime.dwLowDateTime=v_ui.LowPart;
    v_ftime.dwHighDateTime=v_ui.HighPart;
    FileTimeToSystemTime(&v_ftime,&t_res);
    return t_res;
}
Andre Kirpitch
  • 1,027
  • 11
  • 18
  • If right is a few seconds earlier then left...then it looks like you get a really big time as your answer? SYSTEMTIME is made of WORD members (unsigned), so it cannot represent negative time differences. – Gabe Halsmer Jul 29 '17 at 22:02
  • with modern C++ `ULARGE_INTEGER`s can be subtracted as is without copying them into `__int64`s – AntonK Jun 29 '23 at 16:53
7

It says pretty clearly on the MSDN documentation:

It is not recommended that you add and subtract values from the SYSTEMTIME structure to obtain relative times. Instead, you should

  • Convert the SYSTEMTIME structure to a FILETIME structure.
  • Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
  • Use normal 64-bit arithmetic on the ULARGE_INTEGER value.

Why not do exactly that?

bobbymcr
  • 23,769
  • 3
  • 56
  • 67
  • 1
    i wanted to avoid this. but, I'll do what you suggested. how do i deduct the two ULARGE_INTEGER structure i created? – kakush Jan 02 '12 at 09:20
  • You can just use a 64-bit int type for that. As also stated on MSDN ( http://msdn.microsoft.com/en-us/library/aa383742(v=VS.85).aspx ): Your C compiler may support 64-bit integers natively. For example, Microsoft Visual C++ supports the __int64 sized integer type. For more information, see the documentation included with your C compiler. – bobbymcr Jan 02 '12 at 09:24
6

ft1 and ft2 are filetime structures

ULARGE_INTEGER ul1;
    ul1.LowPart = ft1.dwLowDateTime;
    ul1.HighPart = ft1.dwHighDateTime;

ULARGE_INTEGER ul2;
    ul2.LowPart = ft2.dwLowDateTime;
    ul2.HighPart = ft2.dwHighDateTime;


ul2.QuadPart -= ul1.QuadPart;

Difference in Milliseconds...

ULARGE_INTEGER uliRetValue;
    uliRetValue.QuadPart = 0;


    uliRetValue = ul2;
    uliRetValue.QuadPart /= 10;
    uliRetValue.QuadPart /= 1000; // To Milliseconds
João Augusto
  • 2,285
  • 24
  • 28