a34fd83277723d9397905669bc8a47451ef10a1b
[evhz] / evhz.c
1 #include <string.h>
2 #include <stdio.h>
3 #include <linux/input.h>
4 #include <fcntl.h>
5 #include <signal.h>
6 #include <getopt.h>
7 #include <unistd.h>
8
9 #define EVENTS 50
10 #define HZ_LIST 64
11
12 typedef struct event_s {
13 int fd;
14 int hz[HZ_LIST];
15 int count;
16 int avghz;
17 double prvtime;
18 char name[128];
19 } event_t;
20
21 int quit = 0;
22
23 void sigint() {
24 quit = 1;
25 }
26
27 int main(int argc, char *argv[]) {
28 int optch;
29 int i;
30 event_t events[EVENTS];
31 int verbose = 0;
32
33 while((optch = getopt(argc, argv, "hv")) != -1) {
34 switch(optch) {
35 case('h'):
36 printf("Usage: %s [-v|-h]\n", argv[0]);
37 return 0;
38 break;
39 case('v'):
40 verbose = 1;
41 break;
42 }
43 }
44
45 signal(SIGINT, sigint);
46
47 printf("Press CTRL-C to exit.\n\n");
48
49 memset(events, 0, sizeof(events));
50
51 // List input devices
52 for(i = 0; i < EVENTS; i++) {
53 char device[18];
54
55 sprintf(device, "/dev/input/event%i", i);
56 events[i].fd = open(device, O_RDONLY);
57
58 if(events[i].fd != -1) {
59 ioctl(events[i].fd, EVIOCGNAME(sizeof(events[i].name)), events[i].name);
60 if(verbose) printf("event%i: %s\n", i, events[i].name);
61 }
62 }
63
64 while(!quit) {
65 fd_set set;
66
67 FD_ZERO(&set);
68
69 for(i = 0; i < EVENTS; i++) {
70 if(events[i].fd != -1) {
71 FD_SET(events[i].fd, &set);
72 }
73 }
74
75 if(select(FD_SETSIZE, &set, NULL, NULL, NULL) > 0) {
76 int bytes;
77 struct input_event event;
78
79 for(i = 0; i < EVENTS; i++) {
80 if(events[i].fd == -1 || !FD_ISSET(events[i].fd, &set)) {
81 continue;
82 }
83
84 bytes = read(events[i].fd, &event, sizeof(event));
85
86 if(bytes != sizeof(event)) {
87 continue;
88 }
89
90 if(event.type == EV_REL) {
91 double time;
92 int hz;
93
94 time = event.time.tv_sec * 1000 + event.time.tv_usec / 1000;
95 hz = 1000 / (time - events[i].prvtime);
96
97 if(hz > 0) {
98 int j;
99
100 events[i].count++;
101 events[i].hz[events[i].count & (HZ_LIST - 1)] = hz;
102
103 events[i].avghz = 0;
104
105 for(j = 0; j < HZ_LIST; j++) {
106 events[i].avghz += events[i].hz[j];
107 }
108
109 events[i].avghz /= (events[i].count > HZ_LIST) ? HZ_LIST : events[i].count;
110
111 if(verbose) printf("%s: Latest % 5iHz, Average % 5iHz\n", events[i].name, hz, events[i].avghz);
112 }
113
114 events[i].prvtime = time;
115 }
116 }
117 }
118 }
119
120 for(i = 0; i < EVENTS; i++) {
121 if(events[i].fd != -1) {
122 if (events[i].avghz != 0) {
123 printf("\nAverage for %s: % 5iHz\n", events[i].name, events[i].avghz);
124 }
125 close(events[i].fd);
126 }
127 }
128
129 return 0;
130 }