bh_time.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. uint32 bh_get_tick_sec()
  42. {
  43. return _bh_time_get_boot_millisecond() / 1000;
  44. }
  45. /*
  46. * This function returns GMT time milliseconds since from 1970.1.1, AKA UNIX time.
  47. * @return milliseconds since from 1970.1.1.
  48. */
  49. uint64 _bh_time_get_millisecond_from_1970()
  50. {
  51. struct timeb tp;
  52. ftime(&tp);
  53. return ((uint64) tp.time) * 1000 + tp.millitm
  54. - (tp.dstflag == 0 ? 0 : 60 * 60 * 1000) + tp.timezone * 60 * 1000;
  55. }
  56. size_t _bh_time_strftime(char *s, size_t max, const char *format, int64 time)
  57. {
  58. time_t time_sec = time / 1000;
  59. struct timeb tp;
  60. struct tm *ltp;
  61. ftime(&tp);
  62. time_sec -= tp.timezone * 60;
  63. ltp = localtime(&time_sec);
  64. if (ltp == NULL) {
  65. return 0;
  66. }
  67. return strftime(s, max, format, ltp);
  68. }