Add clock() polyfill on Windows (#279)

We normally use CLOCK_PROCESS_CPUTIME_ID but there's no clock_gettime()
on Windows NT.
This commit is contained in:
Paul Kulchenko 2021-09-28 02:14:24 -07:00 committed by GitHub
parent 39bf41f4eb
commit 9cabdaabfd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -19,6 +19,11 @@
#include "libc/calls/struct/timespec.h"
#include "libc/sysv/consts/clock.h"
#include "libc/time/time.h"
#include "libc/dce.h"
#include "libc/nt/synchronization.h"
#include "libc/nt/runtime.h"
#include "libc/nt/accounting.h"
#include "libc/fmt/conv.h"
/**
* Returns how much CPU program has consumed on time-sharing system.
@ -28,7 +33,17 @@
*/
int64_t clock(void) {
struct timespec ts;
if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == -1) return -1;
struct NtFileTime creation_time, exit_time, kernel_time, user_time;
int64_t proc, total;
// polyfill on Windows where CLOCK_PROCESS_CPUTIME_ID may be not available
if (IsWindows() && CLOCK_PROCESS_CPUTIME_ID == -1) {
proc = GetCurrentProcess();
if (!GetProcessTimes(proc, &creation_time,
&exit_time, &kernel_time, &user_time)) return -1;
total = ReadFileTime(kernel_time) + ReadFileTime(user_time);
ts = WindowsDurationToTimeSpec(total);
}
else if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == -1) return -1;
return ts.tv_sec * CLOCKS_PER_SEC +
ts.tv_nsec / (1000000000 / CLOCKS_PER_SEC);
}