Skip to content

Commit

Permalink
fixup! Benchmark: emulate clock_gettime(2) on Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
aklomp committed Jan 9, 2024
1 parent 0a8de55 commit 3d8cbb8
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 4 deletions.
20 changes: 16 additions & 4 deletions test/benchmark.c
Expand Up @@ -130,18 +130,30 @@ timediff_sec (base64_timespec *start, base64_timespec *end)

return (float)((diff * tb.numer) / tb.denom) / 1e9f;
}
#elif defined(_WIN32) && !(defined(__MINGW32__) || defined(__MINGW64__))
typedef struct timespec base64_timespec;
#elif defined(_WIN32)
typedef ULARGE_INTEGER base64_timespec;

static void
base64_gettime (base64_timespec *o_time)
{
timespec_get(o_time, TIME_UTC);
FILETIME current_time_ft;

GetSystemTimePreciseAsFileTime(&current_time_ft);

o_time->LowPart = current_time_ft.dwLowDateTime;
o_time->HighPart = current_time_ft.dwHighDateTime;
}

static float
timediff_sec (base64_timespec *start, base64_timespec *end)
{
return (end->tv_sec - start->tv_sec) + ((float)(end->tv_nsec - start->tv_nsec)) / 1e9f;
float ssec = start->QuadPart / 10000000f;
float snsec = (start->QuadPart % 10000000f) * 100f;

float esec = end->QuadPart / 10000000f;
float ensec = (end->QuadPart % 10000000f) * 100f;

return (esec - ssec) + (ensec - snsec) / 1e9f;
}
#else
typedef struct timespec base64_timespec;
Expand Down
46 changes: 46 additions & 0 deletions test/gettime_win.c
@@ -0,0 +1,46 @@
#include <windows.h>
#include <time.h>

#ifndef CLOCK_REALTIME
#define CLOCK_REALTIME 2
#endif

/* Number of 100 ns intervals from January 1, 1601 till January 1, 1970. */
#define UNIX_EPOCH 116444736000000000ULL

#ifndef _TIMESPEC_DEFINED
struct timespec {
time_t tv_sec;
long tv_nsec;
};
#endif

static ULARGE_INTEGER
xgetfiletime (void)
{
ULARGE_INTEGER current_time;
FILETIME current_time_ft;

/* Returns current time in UTC as a 64-bit value representing the number
* of 100-nanosecond intervals since January 1, 1601 . */
GetSystemTimePreciseAsFileTime(&current_time_ft);
current_time.LowPart = current_time_ft.dwLowDateTime;
current_time.HighPart = current_time_ft.dwHighDateTime;

return current_time;
}

static int
clock_gettime (clock_t id, struct timespec* ts)
{
if (id != CLOCK_REALTIME)
return -1;

ULARGE_INTEGER current_time = xgetfiletime();

/* Time from Epoch to now. */
ts->tv_sec = (current_time.QuadPart - UNIX_EPOCH) / 10000000;
ts->tv_nsec = ((current_time.QuadPart - UNIX_EPOCH) % 10000000) * 100;

return 0;
}

0 comments on commit 3d8cbb8

Please sign in to comment.