bh_time.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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/time.h>
  9. /*
  10. * This function returns milliseconds per tick.
  11. * @return milliseconds per tick.
  12. */
  13. uint64 _bh_time_get_tick_millisecond()
  14. {
  15. return (uint64)sysconf(_SC_CLK_TCK);
  16. }
  17. /*
  18. * This function returns milliseconds after boot.
  19. * @return milliseconds after boot.
  20. */
  21. uint64 _bh_time_get_boot_millisecond()
  22. {
  23. struct timespec ts;
  24. if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
  25. return 0;
  26. }
  27. return ((uint64) ts.tv_sec) * 1000 + ((uint64)ts.tv_nsec) / (1000 * 1000);
  28. }
  29. uint32 bh_get_tick_sec()
  30. {
  31. return (uint32)(_bh_time_get_boot_millisecond() / 1000);
  32. }
  33. /*
  34. * This function returns GMT time milliseconds since from 1970.1.1, AKA UNIX time.
  35. * @return milliseconds since from 1970.1.1.
  36. */
  37. uint64 _bh_time_get_millisecond_from_1970()
  38. {
  39. struct timeval tv;
  40. struct timezone tz;
  41. gettimeofday(&tv, &tz);
  42. return tv.tv_sec * 1000 + tv.tv_usec
  43. - (tz.tz_dsttime == 0 ? 0 : 60 * 60 * 1000)
  44. + tz.tz_minuteswest * 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 timeval tv;
  50. struct timezone tz;
  51. struct tm *ltp;
  52. gettimeofday(&tv, &tz);
  53. time_sec -= tz.tz_minuteswest * 60;
  54. ltp = localtime(&time_sec);
  55. if (ltp == NULL) {
  56. return 0;
  57. }
  58. return strftime(s, max, format, ltp);
  59. }