~iank/evhz

04261c1142b015c6995a1a635e5e8aa70bf873ca — Tobias Jakobi 7 years ago 7a9bfe1
Use proper 64-bit integer arithmetic for Hz calculation

The current code uses double floats, which makes no sense since
time differences are always integer and never fractional.

Also fix up the averaging code a bit.

This fixes some spurious wrong Hz values reported for
my Logitech Rumblepad 2.

Signed-off-by: Tobias Jakobi <tjakobi@math.uni-bielefeld.de>
1 files changed, 15 insertions(+), 8 deletions(-)

M evhz.c
M evhz.c => evhz.c +15 -8
@@ 27,7 27,7 @@ typedef struct event_s {
    int hz[HZ_LIST];
    int count;
    int avghz;
    double prev_time;
    unsigned long long prev_time;
    char name[128];
} event_t;



@@ 115,25 115,32 @@ int main(int argc, char *argv[]) {
            }

            if(event.type == EV_REL || event.type == EV_ABS) {
                double time;
                int hz;
                unsigned long long time, timediff;
                unsigned hz = 0;

                time = event.time.tv_sec * 1000 + event.time.tv_usec / 1000;
                hz = 1000 / (time - events[i].prev_time);
                time = (unsigned long long)event.time.tv_sec * 1000ULL;
                time += (unsigned long long)event.time.tv_usec / 1000ULL;

                timediff = time - events[i].prev_time;

                if(timediff != 0)
                    hz = 1000ULL / timediff;

                if(hz > 0) {
                    int j;
                    unsigned j, maxavg;

                    events[i].count++;
                    events[i].hz[events[i].count & (HZ_LIST - 1)] = hz;

                    events[i].avghz = 0;

                    for(j = 0; j < HZ_LIST; j++) {
                    maxavg = (events[i].count > HZ_LIST) ? HZ_LIST : events[i].count;

                    for(j = 0; j < maxavg; j++) {
                        events[i].avghz += events[i].hz[j];
                    }

                    events[i].avghz /= (events[i].count > HZ_LIST) ? HZ_LIST : events[i].count;
                    events[i].avghz /= maxavg;

                    if(verbose) printf("%s: Latest % 5iHz, Average % 5iHz\n", events[i].name, hz, events[i].avghz);
                }