Skip to content

Instantly share code, notes, and snippets.

@satoru-takeuchi
Created September 24, 2021 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save satoru-takeuchi/2b6510da8f8c4de78ca2236f0ef3a987 to your computer and use it in GitHub Desktop.
Save satoru-takeuchi/2b6510da8f8c4de78ca2236f0ef3a987 to your computer and use it in GitHub Desktop.
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <err.h>
#define NLOOP_FOR_ESTIMATION 1000000000UL
#define NSECS_PER_MSEC 1000000UL
#define NSECS_PER_SEC 1000000000UL
#define TOTAL 100
static unsigned long nloop_per_msec;
static struct timespec start;
struct timespec *logbuf;
static inline long diff_nsec(struct timespec before, struct timespec after)
{
return ((after.tv_sec * NSECS_PER_SEC + after.tv_nsec)
- (before.tv_sec * NSECS_PER_SEC + before.tv_nsec));
}
static unsigned long estimate_loops_per_msec()
{
struct timespec before, after;
clock_gettime(CLOCK_MONOTONIC, &before);
unsigned long i;
for (i = 0; i < NLOOP_FOR_ESTIMATION; i++)
;
clock_gettime(CLOCK_MONOTONIC, &after);
return NLOOP_FOR_ESTIMATION * NSECS_PER_MSEC / diff_nsec(before, after);
}
static void child_fn(int id)
{
struct timespec buf[TOTAL];
int i;
for (i = 0; i < TOTAL; i++) {
struct timespec now;
unsigned long j;
for (j = 0; j < nloop_per_msec; j++)
;
clock_gettime(CLOCK_MONOTONIC, &now);
buf[i] = now;
}
for (i = 0; i < TOTAL; i++) {
printf("%d\t%ld\t%d\n", id, diff_nsec(start, buf[i]) / NSECS_PER_MSEC, (i+1)*100/TOTAL);
}
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[])
{
if (argc < 2) {
fprintf(stderr, "使い方: %s <nproc>\n", argv[0]);
exit(EXIT_FAILURE);
}
int nproc = atoi(argv[1]);
if (nproc < 1) {
fprintf(stderr, "<nproc>(%d)は1以上にしてください\n", nproc);
exit(EXIT_FAILURE);
}
nloop_per_msec = estimate_loops_per_msec();
fflush(stdout);
clock_gettime(CLOCK_MONOTONIC, &start);
int i;
for (i = 0; i < nproc; i++) {
pid_t pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
} else if (pid == 0) {
child_fn(i);
abort();
}
}
for (i = 0; i < nproc; i++)
wait(NULL);
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment