Last active
June 20, 2017 14:02
-
-
Save betseg/efa8fe25bdd7eb322b11950099020531 to your computer and use it in GitHub Desktop.
reaction timer test thing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/time.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <termios.h> | |
#include <ctype.h> | |
#include <stdbool.h> | |
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1) { | |
long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); | |
result->tv_sec = diff / 1000000; | |
result->tv_usec = diff % 1000000; | |
return (diff<0); | |
} | |
void p_elapsedtime(struct timeval *tv){ | |
printf("\n%ld.%06lds\n\n", tv->tv_sec, tv->tv_usec); | |
} | |
void setterm() { | |
struct termios info; | |
tcgetattr(0, &info); | |
info.c_lflag &= ~ICANON; | |
info.c_cc[VMIN] = 1; | |
info.c_cc[VTIME] = 0; | |
tcsetattr(0, TCSANOW, &info); | |
} | |
bool play(double *average, int *times) { | |
(*times)++; | |
struct timeval tvBegin, tvEnd, tvDiff; | |
int r = (rand() % 10) + 5; | |
puts("Press any key to start, or press 'q' to exit."); | |
if(toupper(getchar()) == 'Q') return false; | |
usleep(r * 100000); | |
puts("\nPress any key to end the timer!"); | |
gettimeofday(&tvBegin, NULL); | |
getchar(); | |
gettimeofday(&tvEnd, NULL); | |
timeval_subtract(&tvDiff, &tvEnd, &tvBegin); | |
p_elapsedtime(&tvDiff); | |
*average = *times == 1 | |
? (tvDiff.tv_sec + (double)((double)tvDiff.tv_usec / 1000000)) | |
: ((*average * (*times-1) / *times) + (double)(tvDiff.tv_sec + (double)((double)tvDiff.tv_usec / 1000000))/ * times); | |
} | |
int main(int argc, char *argv[]) { | |
srand(time(NULL)); | |
setterm(); | |
double average = 0; | |
int times = 0; | |
while(play(&average, ×)); | |
printf("\n\nAverage: %.6fs\n", average); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment