Advertisement
gocha

時間計測・時間待ち関数群(Windows/Linux)

May 16th, 2013
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6. #ifdef WIN32
  7. #include <windows.h>
  8. #else
  9. #include <unistd.h>
  10. #include <sys/time.h>
  11. #endif
  12.  
  13. // 時間計測関数の使用前処理
  14. void InitTimer(void)
  15. {
  16. #ifdef WIN32
  17.     timeBeginPeriod(1);
  18. #endif /* WIN32 */
  19. }
  20.  
  21. // 時間計測関数の使用後処理
  22. void UnInitTimer(void)
  23. {
  24. #ifdef WIN32
  25.     timeEndPeriod(1);
  26. #endif /* WIN32 */
  27. }
  28.  
  29. // 時間取得関数(秒)
  30. double GetTimeVal(void)
  31. {
  32. #ifdef WIN32
  33.     return (double)(timeGetTime()) / 1000;
  34. #else
  35.     struct timeval t;
  36.     gettimeofday(&t, NULL);
  37.     return (double)t.tv_sec + (double)t.tv_usec * 1e-6;
  38. #endif
  39. }
  40.  
  41. // 時間待ち関数(秒)
  42. void SysSleep(double tsleep)
  43. {
  44. #ifdef WIN32
  45.     Sleep((DWORD)(tsleep * 1000));
  46. #else
  47.     struct timespec treq, trem;
  48.     treq.tv_sec = (time_t)tsleep;
  49.     treq.tv_nsec = (long)((tsleep - treq.tv_sec) * 1000000000.0);
  50.     memset(&trem, 0, sizeof(trem));
  51.     nanosleep(&treq, &trem);
  52. #endif
  53. }
  54.  
  55. // 現在時刻出力関数
  56. void PrintTime(void)
  57. {
  58. #ifdef WIN32
  59.     SYSTEMTIME t_st;
  60.     GetLocalTime(&t_st);
  61.     printf("%d-%02d-%02d %02d:%02d:%02d.%03d\n",
  62.         t_st.wYear,
  63.         t_st.wMonth,
  64.         t_st.wDay,
  65.         t_st.wHour,
  66.         t_st.wMinute,
  67.         t_st.wSecond,
  68.         t_st.wMilliseconds);
  69. #else
  70.     struct timeval tv;
  71.     struct tm *t_st;
  72.  
  73.     /* 現在時刻の取得 */
  74.     gettimeofday(&tv, NULL);
  75.  
  76.     /* 現在時刻を構造体に変換 */
  77.     t_st = localtime(&tv.tv_sec);
  78.     printf("%d-%02d-%02d %02d:%02d:%02d.%03d\n",
  79.         t_st->tm_year + 1900,
  80.         t_st->tm_mon + 1,
  81.         t_st->tm_mday,
  82.         t_st->tm_hour,
  83.         t_st->tm_min,
  84.         t_st->tm_sec,
  85.         (int)(tv.tv_usec / 10000));
  86. #endif /* WIN32 */
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement