cube-test.c 1.93 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*
 * 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>
Kevin Lyda's avatar
Kevin Lyda committed
11
#include <sys/time.h>
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29

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;
  }
30
  buf[9] = 0;
31 32 33
  return atoi(buf);
}

Kevin Lyda's avatar
Kevin Lyda committed
34
typedef struct interval_timer_struct {
Kevin Lyda's avatar
Kevin Lyda committed
35
  struct timeval then;
Kevin Lyda's avatar
Kevin Lyda committed
36
} interval_timer_t;
Kevin Lyda's avatar
Kevin Lyda committed
37 38

void
Kevin Lyda's avatar
Kevin Lyda committed
39
start_timer(interval_timer_t *timer) {
Kevin Lyda's avatar
Kevin Lyda committed
40 41 42 43
  gettimeofday(&timer->then, NULL);
}

long int
Kevin Lyda's avatar
Kevin Lyda committed
44
end_timer(interval_timer_t *timer) {
Kevin Lyda's avatar
Kevin Lyda committed
45 46 47 48 49 50 51 52 53 54
  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;
}

55 56 57 58 59 60 61 62 63 64 65 66 67 68
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;
}

69 70
int
main(int argc, char *argv[]) {
71
  int guess, number, iterations = 0, correct = 0;
Kevin Lyda's avatar
Kevin Lyda committed
72
  interval_timer_t timer;
73
  long int delta, delta_total = 0;
74 75 76 77 78 79

  srand(time(NULL));

  while (1) {
    number = random_two_digit_number();
    printf("Number is %d. Cube root (0 to exit)? ", cube(number));
Kevin Lyda's avatar
Kevin Lyda committed
80
    start_timer(&timer);
81
    guess = read_number();
Kevin Lyda's avatar
Kevin Lyda committed
82
    delta = end_timer(&timer);
83
    if (guess == 0) {
84 85 86 87 88
      if (iterations) {
        printf("Got %d correct out of %d.\n", correct, iterations);
        printf("Average time to answer was %s\n",
            humanize_usec(delta_total / iterations));
      }
89 90
      exit(0);
    }
91 92
    iterations++;
    delta_total += delta;
93
    if (guess == number) {
94
      correct++;
95 96 97 98
      printf("Correct.\n");
    } else {
      printf("Not correct. Number was %d.\n", number);
    }
99
    printf("Took %s\n", humanize_usec(delta));
100 101
  }
}