main.c
Example source referenced by the lesson. It does not run on this site. Learn
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
uint64_t count_steps(uint64_t n);
static double now(void) {
struct timespec t;
if (clock_gettime(CLOCK_MONOTONIC, &t) != 0) {
perror("clock_gettime");
exit(1);
}
return (double)t.tv_sec + (double)t.tv_nsec / 1e9;
}
int main(int argc, char **argv) {
if (argc != 2 || argv[1][0] < '0' || argv[1][0] > '9') {
fprintf(stderr, "usage: %s N (0..100000000)\n", argv[0]);
return 2;
}
errno = 0;
char *end;
uintmax_t input = strtoumax(argv[1], &end, 10);
if (errno || *end || input > 100000000) {
fprintf(stderr, "N must be an integer from 0 to 100000000\n");
return 2;
}
uint64_t n = (uint64_t)input;
double start = now();
uint64_t result = count_steps(n);
double elapsed = now() - start;
printf("n=%" PRIu64 " result=%" PRIu64 " elapsed_seconds=%.9f\n",
n, result, elapsed);
return result == n ? 0 : 1;
}