bh_time.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include "bh_time.h"
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. //#include <sys/timeb.h>
  9. #include <time.h>
  10. /*
  11. * This function returns milliseconds per tick.
  12. * @return milliseconds per tick.
  13. */
  14. uint64 _bh_time_get_tick_millisecond()
  15. {
  16. return sysconf(_SC_CLK_TCK);
  17. }
  18. /*
  19. * This function returns milliseconds after boot.
  20. * @return milliseconds after boot.
  21. */
  22. uint64 _bh_time_get_boot_millisecond()
  23. {
  24. struct timespec ts;
  25. if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
  26. return 0;
  27. }
  28. return ((uint64) ts.tv_sec) * 1000 + ts.tv_nsec / (1000 * 1000);
  29. }
  30. /*
  31. * This function returns GMT time milliseconds since from 1970.1.1, AKA UNIX time.
  32. * @return milliseconds since from 1970.1.1.
  33. */
  34. uint64 _bh_time_get_millisecond_from_1970()
  35. {
  36. struct timeval tv;
  37. gettimeofday(&tv, NULL);
  38. uint64 millisecondsSinceEpoch = (uint64_t)(tv.tv_sec) * 1000
  39. + (uint64_t)(tv.tv_usec) / 1000;
  40. return millisecondsSinceEpoch;
  41. }
  42. size_t _bh_time_strftime(char *s, size_t max, const char *format, int64 time)
  43. {
  44. time_t time_sec = time / 1000;
  45. struct tm *ltp;
  46. ltp = localtime(&time_sec);
  47. if (ltp == NULL) {
  48. return 0;
  49. }
  50. return strftime(s, max, format, ltp);
  51. }