Elapsed Time
There is a need for measuring elapsed time. This code seems to work well:
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
#include <mraa.h>
int main(void) {
double elapsedTime;
struct timespec ts_start;
struct timespec ts_end;
// start timer
clock_gettime(CLOCK_MONOTONIC, &ts_start);
// do something
usleep(1000000);
// stop timer
clock_gettime(CLOCK_MONOTONIC, &ts_end);
// compute and print the elapsed time in millisec
elapsedTime=(ts_end.tv_sec-ts_start.tv_sec)*1000.0; // sec to ms
elapsedTime+=(ts_end.tv_nsec-ts_start.tv_nsec)/1000000.0; // nsec to ms
printf("Elapsed time %lf ms\n",elapsedTime);
// start timer
clock_gettime(CLOCK_MONOTONIC, &ts_start);
// stop timer
clock_gettime(CLOCK_MONOTONIC, &ts_end);
// compute and print the elapsed time in millisec
elapsedTime=(ts_end.tv_sec-ts_start.tv_sec)*1000.0; // sec to ms
elapsedTime+=(ts_end.tv_nsec-ts_start.tv_nsec)/1000000.0; // nsec to ms
printf("Elapsed time adjustment %lf ms\n",elapsedTime);
return 0;
}
It is pretty consistent:
root@mylinkit:~/Code# ./elapsedTime.run
Elapsed time 1000.084598 ms
Elapsed time adjustment 0.001242 ms
root@mylinkit:~/Code# ./elapsedTime.run
Elapsed time 1000.079080 ms
Elapsed time adjustment 0.001376 ms
root@mylinkit:~/Code# ./elapsedTime.run
Elapsed time 1000.083097 ms
Elapsed time adjustment 0.001431 ms
root@mylinkit:~/Code# ./elapsedTime.run
Elapsed time 1000.081609 ms
Elapsed time adjustment 0.001255 ms
root@mylinkit:~/Code# ./elapsedTime.run
Elapsed time 1000.079716 ms
Elapsed time adjustment 0.001248 ms
root@mylinkit:~/Code# ./elapsedTime.run
Elapsed time 1000.080426 ms
Elapsed time adjustment 0.001445 ms
The "elsaped time adjustment (~1.33 uS) is the time it takes to do the measurement.
The "usleep()" function is off about 81 us (over 1000000 uS) which seem consistent with the definition that:
- " The usleep() function suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any
system activity or by the time spent processing the call or by the granularity of system timers."
So all good!
AlanX
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.