Close

Elapsed Time

A project log for Setting up the LinkIt C cross-compiler

Are you a "dyed in the wool" C programmer. Love your Arduino but want something more powerful. The LinkIt Smart MT7688 board may for you!

agpcooperagp.cooper 11/02/2017 at 10:290 Comments

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:

So all good!

AlanX

Discussions