Minor changes
[matilda.git] / src / timem.c
blob213d458aace0bbdb798eefded71aa04cb087d466
1 /*
2 Generic time-keeping functions and Go time system related functions. All times
3 are in milliseconds.
4 */
6 #include "config.h"
8 #include <time.h>
9 #include <unistd.h>
10 #include <stdio.h>
12 #ifdef __MACH__
13 #include <mach/clock.h>
14 #include <mach/mach.h>
15 #endif
17 #include "alloc.h"
18 #include "types.h"
22 Returns a current time mark with millisecond precision. Will be monotonic if
23 supported by the system. Is thread-safe.
24 RETURNS time in milliseconds
26 u64 current_time_in_millis() {
27 struct timespec ts;
29 #ifdef __MACH__
31 macOS
33 clock_serv_t cclock;
34 mach_timespec_t mts;
35 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
36 clock_get_time(cclock, &mts);
37 mach_port_deallocate(mach_task_self(), cclock);
38 ts.tv_sec = mts.tv_sec;
39 ts.tv_nsec = mts.tv_nsec;
41 #else
43 Linux, BSD
45 /* POSIX.1 conforming */
46 #ifdef _POSIX_MONOTONIC_CLOCK
47 clock_gettime(CLOCK_MONOTONIC, &ts);
48 #else
49 clock_gettime(CLOCK_REALTIME, &ts);
50 #endif
51 #endif
53 u64 ret = ts.tv_sec * 1000;
54 ret += ts.tv_nsec / 1000000;
55 return ret;
59 Returns the current nanoseconds count from the system clock. Is not monotonic.
60 RETURNS nanoseconds
62 u64 current_nanoseconds() {
63 struct timespec ts;
65 #ifdef __MACH__
67 macOS
69 clock_serv_t cclock;
70 mach_timespec_t mts;
71 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
72 clock_get_time(cclock, &mts);
73 mach_port_deallocate(mach_task_self(), cclock);
74 ts.tv_sec = mts.tv_sec;
75 ts.tv_nsec = mts.tv_nsec;
77 #else
79 Linux, BSD
81 /* POSIX.1 conforming */
82 #ifdef _POSIX_MONOTONIC_CLOCK
83 clock_gettime(CLOCK_MONOTONIC, &ts);
84 #else
85 clock_gettime(CLOCK_REALTIME, &ts);
86 #endif
87 #endif
89 return ts.tv_nsec;
93 Produces a textual timestamp based on the local timezone and system time.
95 void timestamp(
96 char * buffer
97 ) {
98 time_t t = time(NULL);
99 struct tm tm = *localtime(&t);
101 snprintf(buffer, MAX_PAGE_SIZ, "%02u:%02u:%02u", tm.tm_hour, tm.tm_min, tm.tm_sec);