bh_time.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 (uint64)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 + ((uint64)ts.tv_nsec) / (1000 * 1000);
  29. }
  30. uint32 bh_get_tick_sec()
  31. {
  32. return (uint32)(_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)
  44. + ((uint64)tp.timezone) * 60 * 1000;
  45. }
  46. size_t _bh_time_strftime(char *s, size_t max, const char *format, int64 time)
  47. {
  48. time_t time_sec = (time_t)(time / 1000);
  49. struct timeb tp;
  50. struct tm *ltp;
  51. ftime(&tp);
  52. time_sec -= tp.timezone * 60;
  53. ltp = localtime(&time_sec);
  54. if (ltp == NULL) {
  55. return 0;
  56. }
  57. return strftime(s, max, format, ltp);
  58. }