time_utils.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #ifndef CHAPTER10_INCLUDE_TIME_UTILS_H_
  2. #define CHAPTER10_INCLUDE_TIME_UTILS_H_
  3. #include <io_utils.h>
  4. #if defined(_WIN32)
  5. #include <sys/timeb.h>
  6. #elif defined(__unix__) || defined(__APPLE__)
  7. #include <sys/time.h>
  8. #endif
  9. typedef long long long_time_t;
  10. long_time_t TimeInMillisecond(void) {
  11. #if defined(_WIN32)
  12. struct timeb time_buffer;
  13. ftime(&time_buffer);
  14. return time_buffer.time * 1000LL + time_buffer.millitm;
  15. #elif defined(__unix__) || defined(__APPLE__)
  16. struct timeval time_value;
  17. gettimeofday(&time_value, NULL);
  18. return time_value.tv_sec * 1000LL + time_value.tv_usec / 1000;
  19. #elif defined(__STDC__) && __STDC_VERSION__ == 201112L
  20. struct timespec timespec_value;
  21. timespec_get(&timespec_value, TIME_UTC);
  22. return timespec_value.tv_sec * 1000LL + timespec_value.tv_nsec / 1000000;
  23. #else
  24. time_t current_time = time(NULL);
  25. return current_time * 1000LL;
  26. #endif
  27. }
  28. void TimeCost(char const* msg) {
  29. static long_time_t start_time = 0;
  30. if (msg && start_time != 0) {
  31. long_time_t current_time = TimeInMillisecond();
  32. PRINTLNF("%s costs: %lld", msg, current_time - start_time);
  33. }
  34. start_time = TimeInMillisecond();
  35. }
  36. //void SleepMs(long milliseconds) {
  37. // long seconds = milliseconds / 1000;
  38. // long nanoseconds = (milliseconds % 1000) * 1000000L;
  39. // thrd_sleep(&(struct timespec) {.tv_sec=seconds, .tv_nsec=nanoseconds}, NULL);
  40. //}
  41. #endif //CHAPTER10_INCLUDE_TIME_UTILS_H_