Select Git revision
cube-test.c
Kevin Lyda authored
cube-test.c 1.83 KiB
/*
* cube-test.c
* Copyright (C) 2017 Kevin Lyda <kevin@phrye.com>
*
* Distributed under terms of the GPL license.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
int
random_two_digit_number() {
return (rand() % 90) + 10;
}
int
cube(int n) {
return n * n * n;
}
int
read_number() {
char buf[10];
if (!fgets(buf, sizeof buf, stdin)) {
return 0;
}
return atoi(buf);
}
typedef struct timer_struct {
struct timeval then;
} timer_t;
void
start_timer(timer_t *timer) {
gettimeofday(&timer->then, NULL);
}
long int
end_timer(timer_t *timer) {
struct timeval now;
long int delta;
gettimeofday(&now, NULL);
delta = (now.tv_sec - timer->then.tv_sec) * 1000000;
delta += now.tv_usec - timer->then.tv_usec;
return delta;
}
char *
humanize_usec(long int usec) {
static char buf[40];
if (usec < 1000) {
sprintf(buf, "%ldus", usec);
} else if (usec < 1000000) {
sprintf(buf, "%.1fms", usec / 1000.0);
} else {
sprintf(buf, "%.2fs", usec / 1000000.0);
}
return buf;
}
int
main(int argc, char *argv[]) {
int guess, number, iterations = 0, correct = 0; timer_t timer;
long int delta, delta_total = 0;
srand(time(NULL));
while (1) {
number = random_two_digit_number();
printf("Number is %d. Cube root (0 to exit)? ", cube(number));
start_timer(&timer);
guess = read_number();
delta = end_timer(&timer);
if (guess == 0) {
printf("Got %d correct out of %d.\n", correct, iterations);
printf("Average time to answer was %s\n",
humanize_usec(delta_total / iterations));
exit(0);
}
iterations++;
delta_total += delta;
if (guess == number) {
correct++;
printf("Correct.\n");
} else {
printf("Not correct. Number was %d.\n", number);
}
printf("Took %s\n", humanize_usec(delta));
}
}