htime.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include "htime.h"
  2. inline unsigned long long gethrtime() {
  3. #ifdef OS_WIN
  4. static LONGLONG s_freq = 0;
  5. if (s_freq == 0) {
  6. LARGE_INTEGER freq;
  7. QueryPerformanceFrequency(&freq);
  8. s_freq = freq.QuadPart;
  9. }
  10. if (s_freq != 0) {
  11. LARGE_INTEGER count;
  12. QueryPerformanceCounter(&count);
  13. return count.QuadPart / (double)s_freq * 1000000;
  14. }
  15. return 0;
  16. #elif defined(OS_LINUX)
  17. struct timespec ts;
  18. clock_gettime(CLOCK_MONOTONIC, &ts);
  19. return ts.tv_sec*(unsigned long long)1000000 + ts.tv_nsec / 1000;
  20. #else
  21. return clock()* / (double)CLOCKS_PER_SEC * 1000000;
  22. #endif
  23. }
  24. datetime_t get_datetime() {
  25. datetime_t dt;
  26. #ifdef OS_WIN
  27. SYSTEMTIME tm;
  28. GetLocalTime(&tm);
  29. dt.year = tm.wYear;
  30. dt.month = tm.wMonth;
  31. dt.day = tm.wDay;
  32. dt.hour = tm.wHour;
  33. dt.min = tm.wMinute;
  34. dt.sec = tm.wSecond;
  35. dt.ms = tm.wMilliseconds;
  36. #else
  37. struct timeval tv;
  38. struct tm* tm = NULL;
  39. gettimeofday(&tv, NULL);
  40. time_t tt = tv.tv_sec;
  41. tm = localtime(&tt);
  42. dt.year = tm->tm_year + 1900;
  43. dt.month = tm->tm_mon + 1;
  44. dt.day = tm->tm_mday;
  45. dt.hour = tm->tm_hour;
  46. dt.min = tm->tm_min;
  47. dt.sec = tm->tm_sec;
  48. dt.ms = tv.tv_usec/1000;
  49. #endif
  50. return dt;
  51. }
  52. static const char* s_month[] = {"January", "February", "March", "April", "May", "June",
  53. "July", "August", "September", "October", "November", "December"};
  54. int month_atoi(const char* month) {
  55. for (size_t i = 0; i < 12; ++i) {
  56. if (strnicmp(month, s_month[i], strlen(month)) == 0)
  57. return i+1;
  58. }
  59. return 0;
  60. }
  61. const char* month_itoa(int month) {
  62. if (month < 1 || month > 12) {
  63. return NULL;
  64. }
  65. return s_month[month-1];
  66. }
  67. datetime_t get_compile_datetime() {
  68. static datetime_t dt;
  69. char month[32];
  70. sscanf(__DATE__, "%s %d %d", month, &dt.day, &dt.year);
  71. sscanf(__TIME__, "%d %d %d", &dt.hour, &dt.min, &dt.sec);
  72. dt.month = month_atoi(month);
  73. return dt;
  74. }