C++/부팅 시간&경과 시간 구하기

  1. DWORD GetDateAbsSecond(SYSTEMTIME st)
  2. {
  3.     INT64 i64;
  4.     FILETIME fst;
  5.     SystemTimeToFileTime(&st,&fst);
  6.     i64 = (((INT64)fst.dwHighDateTime) << 32) + fst.dwLowDateTime;
  7.     // 초 단위로 환산하고 2000년 1월 1일 자정 기준으로 바꾼다.
  8.     i64 = i64 / 10000000 - (INT64)145731 * 86400;
  9.     return (DWORD)i64;
  10. }
  11. void DateAbsSecondToSystemTime(DWORD Abs, SYSTEMTIME &st)
  12. {
  13.     INT64 i64;
  14.     FILETIME fst;
  15.     i64 = (Abs + (INT64)145731 * 86400) * 10000000;
  16.     fst.dwHighDateTime = (DWORD)(i64 >> 32);
  17.     fst.dwLowDateTime = (DWORD)(i64 & 0xffffffff);
  18.     FileTimeToSystemTime(&fst, &st);
  19. }
  20. SYSTEMTIME GetElapsedTimeSinceBoot()
  21. {
  22.     SYSTEMTIME stRet = { 0, };
  23.     LARGE_INTEGER now, freq;
  24.     // 부팅 후 경과한 시간을 초 단위로 구한다.
  25.     QueryPerformanceCounter(&now);
  26.     QueryPerformanceFrequency(&freq);
  27.     UINT sec = (UINT)(now.QuadPart / freq.QuadPart);
  28.     sec -= 86400 * (stRet.wDay = sec / 86400);
  29.     sec -= 3600 * (stRet.wHour = sec / 3600);
  30.     sec -= 60 * (stRet.wMinute = sec / 60);
  31.     stRet.wSecond = (WORD)(sec);
  32.     return stRet;
  33. }
  34. SYSTEMTIME GetBootTime()
  35. {
  36.     SYSTEMTIME stCurrent = {0,};
  37.     SYSTEMTIME stBootElapsed = GetElapsedTimeSinceBoot();
  38.     SYSTEMTIME stRet = {0,};
  39.     DWORD abs = 0;
  40.     
  41.     // 현재 시간에서 경과 시간을 빼서 부팅한 시간을 구한다.
  42.     GetLocalTime(&stCurrent);
  43.     abs = GetDateAbsSecond(stCurrent);
  44.     DateAbsSecondToSystemTime(abs - stBootElapsed.wSecond, stRet);
  45.     return stRet;
  46. }

SYSTEMTIME st = GetBootTime();
wsprintf(str, _T("부팅 시간: %d월 %d일 %d시 %d분"), st.wMonth, st.wDay, st.wHour, st.wMinute);

-> 부팅 시간: 1월 22일 9시 53분

SYSTEMTIME st = GetElapsedTimeSinceBoot();
wsprintf(str, _T("경과 시간: %d일 %d시 %d분 %d초"), st.wDay, st.wHour, st.wMinute, st.wSecond % 60);

-> 부팅 이후 경과 시간: 0일 0시 52분 5초

See also:
윈도우 시작 이후 경과 시간
  1. #include <mmsystem.h>
  2. // winmm.lib
  3. timeGetTime();

See also:
프로세스 실행 시간
  1. // 현재 시간에서 프로세스 경과 시간을 빼서 프로세스 실행 시간을 구한다.
  2. static SYSTEMTIME stRunning = { 0, };
  3. static double current_sec = 0;
  4. if (current_sec == 0) {
  5.     clock_t current_tick = clock();
  6.     current_sec = current_tick / CLOCKS_PER_SEC;
  7.     SYSTEMTIME stCurrent = { 0, };
  8.     DWORD abs = 0;
  9.     GetLocalTime(&stCurrent);
  10.     abs = GetDateAbsSecond(stCurrent);
  11.     DateAbsSecondToSystemTime(abs - current_sec, stRunning);
  12. }

stRunning.wYear, stRunning.wMonth, stRunning.wDay,
stRunning.wHour, stRunning.wMinute, stRunning.wSecond

이 글에는 0 개의 댓글이 있습니다.