Re-implementation of Izanami game engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

70 lines
1.9 KiB

  1. #include "IZ_timer.h"
  2. #ifdef _WIN64
  3. typedef enum {
  4. _CLOCK_REALTIME = 0,
  5. #define CLOCK_REALTIME _CLOCK_REALTIME
  6. _CLOCK_MONOTONIC = 6,
  7. #define CLOCK_MONOTONIC _CLOCK_MONOTONIC
  8. } clockid_t;
  9. int clock_gettime(clockid_t __clock_id, struct timespec *__tp) {
  10. return timespec_get(__tp, TIME_UTC);
  11. }
  12. #endif
  13. /**
  14. * Gets the start timestamp.
  15. * @sa IZ_TIMER_START_TIMESTAMP
  16. */
  17. void IZ_TimerStart() {
  18. struct timespec t;
  19. clock_gettime(CLOCK_MONOTONIC, &t);
  20. IZ_TIMER_START_TIMESTAMP = t.tv_sec;
  21. }
  22. /**
  23. * Gets the number of microseconds since the application timer has been started.
  24. * @return The number of microseconds.
  25. * @sa IZ_TimerElapsed()
  26. */
  27. unsigned int IZ_TimerElapsedRaw() {
  28. struct timespec t;
  29. clock_gettime(CLOCK_MONOTONIC, &t);
  30. return (t.tv_sec - IZ_TIMER_START_TIMESTAMP) * 1000000 + (t.tv_nsec / 1000);
  31. }
  32. /**
  33. * Gets the formatted elapsed time since the application timer has been started.
  34. * @return The formatted elapsed time.
  35. * @sa IZ_TimerElapsedRaw()
  36. */
  37. char* IZ_TimerElapsed() {
  38. static char buffer[32];
  39. struct timespec t;
  40. clock_gettime(CLOCK_MONOTONIC, &t);
  41. unsigned int seconds = t.tv_sec - IZ_TIMER_START_TIMESTAMP;
  42. unsigned int milliseconds = t.tv_nsec / 1000000;
  43. unsigned int minutes = seconds / 60;
  44. unsigned int hours = seconds / 60 / 60;
  45. sprintf(buffer, "%02d:%02d:%02d.%03d", hours, minutes % 60, seconds % 60, milliseconds % 1000);
  46. return buffer;
  47. }
  48. /**
  49. * Gets the formatted time in the current instant.
  50. * @return The formatted time in the current instant.
  51. */
  52. char* IZ_TimerNow() {
  53. struct timespec t;
  54. clock_gettime(CLOCK_REALTIME, &t);
  55. static char buffer[32];
  56. unsigned int seconds = t.tv_sec;
  57. unsigned int milliseconds = t.tv_nsec / 1000000;
  58. static char formatted[32];
  59. time_t current_time = seconds;
  60. strftime(formatted, sizeof(formatted), "%Y-%m-%dT%H:%M:%S", gmtime(&current_time));
  61. sprintf(buffer, "%s.%03dZ", formatted, milliseconds < 0 ? 0 : milliseconds % 1000);
  62. return buffer;
  63. }