Project

General

Profile

Bug #19461 » localtime_test.c

nobu (Nobuyoshi Nakada), 02/24/2023 02:33 PM

 
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/wait.h>

#define COUNT 10000

static void print_nsec(const char *s, uint64_t n)
{
printf(" %s = %lld.%09u\n", s, n / 1000000000ULL, (unsigned int)(n % 1000000000ULL));
}

void sir_local_alot(int r)
{
struct {
uint64_t start, end;
} monotonic, cputime;
monotonic.start = clock_gettime_nsec_np(CLOCK_MONOTONIC);
cputime.start = clock_gettime_nsec_np(CLOCK_PROCESS_CPUTIME_ID);
time_t t = time(NULL);
if (r) {
for (int i = 0; i < COUNT; ++i) {
struct tm tm;
localtime_r(&t, &tm);
}
}
else {
for (int i = 0; i < COUNT; ++i) {
localtime(&t);
}
}
monotonic.end = clock_gettime_nsec_np(CLOCK_MONOTONIC);
cputime.end = clock_gettime_nsec_np(CLOCK_PROCESS_CPUTIME_ID);
print_nsec("monotonic", monotonic.end - monotonic.start);
print_nsec("cputime", cputime.end - cputime.start);
}

int main(int argc, char **argv)
{
int r = (argc == 2 && *argv[1] == 'r');

printf("Measuring localtime%s\n", r ? "_r" : "");
printf("In parent\n");
sir_local_alot(r);

printf("In child\n");
pid_t pid = fork();
if (!pid) {
sir_local_alot(r);
}
wait(&pid);
return 0;
}
(1-1/3)