bh_time.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "bh_time.h"
  17. #include <unistd.h>
  18. #include <stdio.h>
  19. //#include <sys/timeb.h>
  20. #include <time.h>
  21. /*
  22. * This function returns milliseconds per tick.
  23. * @return milliseconds per tick.
  24. */
  25. uint64 _bh_time_get_tick_millisecond()
  26. {
  27. return sysconf(_SC_CLK_TCK);
  28. }
  29. /*
  30. * This function returns milliseconds after boot.
  31. * @return milliseconds after boot.
  32. */
  33. uint64 _bh_time_get_boot_millisecond()
  34. {
  35. struct timespec ts;
  36. if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
  37. return 0;
  38. }
  39. return ((uint64) ts.tv_sec) * 1000 + ts.tv_nsec / (1000 * 1000);
  40. }
  41. /*
  42. * This function returns GMT time milliseconds since from 1970.1.1, AKA UNIX time.
  43. * @return milliseconds since from 1970.1.1.
  44. */
  45. uint64 _bh_time_get_millisecond_from_1970()
  46. {
  47. struct timeval tv;
  48. gettimeofday(&tv, NULL);
  49. uint64 millisecondsSinceEpoch = (uint64_t)(tv.tv_sec) * 1000
  50. + (uint64_t)(tv.tv_usec) / 1000;
  51. return millisecondsSinceEpoch;
  52. }
  53. size_t _bh_time_strftime(char *s, size_t max, const char *format, int64 time)
  54. {
  55. time_t time_sec = time / 1000;
  56. struct tm *ltp;
  57. ltp = localtime(&time_sec);
  58. if (ltp == NULL) {
  59. return 0;
  60. }
  61. return strftime(s, max, format, ltp);
  62. }