reham.abass
reham.abass

Reputation: 17

How to measure the time in seconds between two characters while user inserting them as an input

How to measure inserting time in seconds?

I tried to use:

struct timeval t1,t2;

I checked time before inserting input:

gettimeofday(&t1,NULL);

and the same after getting the input:

gettimeofday(&t2,NULL);
double elapsedTime=(t2.tv_sec - t1.tv_sec)*10000.0;

but It's not accurate at all !!

I need better way to measure seconds in Inserting time , and to know the differences in seconds in inserting each character.

// trying to insert 5 chars
for(i=0; i<=4 ; i++)
{        
    gettimeofday(&t1,NULL);    //get time before getting char
    c=getchar();
    gettimeofday(&t2,NULL);    //get time after geting char             
    elapsedTime=(t1.tv_sec - t2.tv_sec)*10000.0;
    printf("\n char number %d his elapsed time =%d\n",i,elapsedTime);
}

I need to know the seconds rates, on inserting "clicking" chars as input , and to calculate elapsedTime in seconds :

output should be like:

time between inserting first character and the second is : 0.002 seconds
time between..........second character and the third is:  1.008 seconds

Upvotes: 0

Views: 229

Answers (2)

Solid State
Solid State

Reputation: 124

elapsedTime=(t1.tv_sec - t2.tv_sec)*10000.0;

You're only taking tv_sec into account. the actual timeval struct has a tv_sec and also a tv_usec part which both of them are integers that don't hold fractions (the exact type is not guaranteed though)

tv_sec holds the seconds and tv_usec holds microseconds.

it's also guaranteed that tv_usec is always less than 1000000 that means you only need to calculate the difference of them individually.

and you're also doing t1-t2 that you should change it to t2-t1 as t2 is the latest timeval. this is why you're getting negative times.

elapsedTime=((double) (t2.tv_sec - t1.tv_sec))+((double) (t2.tv_usec - t1.tv_usec) / 1000000.0);

which returns time in : "sec.usec" format that should be precise enough :)

note that you need to declare elapsedTime as double instead of int, and also replace the second "$d" in the printf with "%f".

you also need to consider that keyboard input is buffered which means you're blocked in getchar() until Enter is pressed, then the buffer is fed to getchar, one char at a call. you cad use just Enter as the input character to test the accuracy of the code, but to use it with actual chars, you need to use the unbuffered input.

GNU docs: 21.2 Elapsed Time

Upvotes: 2

user11677651
user11677651

Reputation:

On my system using clock() counts in millisconds, maybe that's accurate enough for your purposes:

#include "time.h"

clock_t c1=clock();
... doing stuff ...
clock_t c2=clock();
printf("diff %i clocks with CLOCKS_PER_SEC = %i\n",c2-c1,CLOCKS_PER_SEC);

Upvotes: 0

Related Questions