bh_time.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. uint32 bh_get_tick_sec()
  31. {
  32. return _bh_time_get_boot_millisecond() / 1000;
  33. }
  34. /*
  35. * This function returns GMT time milliseconds since from 1970.1.1, AKA UNIX time.
  36. * @return milliseconds since from 1970.1.1.
  37. */
  38. uint64 _bh_time_get_millisecond_from_1970()
  39. {
  40. struct timeb tp;
  41. ftime(&tp);
  42. return ((uint64) tp.time) * 1000 + tp.millitm
  43. - (tp.dstflag == 0 ? 0 : 60 * 60 * 1000) + tp.timezone * 60 * 1000;
  44. }
  45. size_t _bh_time_strftime(char *s, size_t max, const char *format, int64 time)
  46. {
  47. time_t time_sec = time / 1000;
  48. struct timeb tp;
  49. struct tm *ltp;
  50. ftime(&tp);
  51. time_sec -= tp.timezone * 60;
  52. ltp = localtime(&time_sec);
  53. if (ltp == NULL) {
  54. return 0;
  55. }
  56. return strftime(s, max, format, ltp);
  57. }