Barath Ravikumar Barath Ravikumar - 6 months ago 15
Linux Question

Calculate execution time when sleep() is used

I am trying to read data from the ADC in the beagle bone, running Angstrom linux distribution. I need to use a delay mechanism like sleep(), to only read samples at specific time, to help conform to a specific sample rate.
I also am required to calculate the execution time.

Here is a sample POC (proof of concept), to demonstrate the problem I am facing:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int main()
{
clock_t begin, end;

while(1)
{
begin = clock();
sleep(1); // delay for 1 sec
end = clock();
printf("Execution time = %f\n",((float)(end-begin)/CLOCKS_PER_SEC));

}

}


I always get the execution time as 0.0;

Why do I not get my result as 1s? My guess is calling sleep() will pre-empt my program, but I am not sure.

What other option do I have, to calculate execution time, which includes a delay?

Answer

The solution to calculate execution time is to get the timestamp at the beginning of your program and at the end. Then make the difference.

#include <stdio.h>
#include <time.h>

int main() {

    time_t begin;
    time(&begin);

  // Somethings

   time_t end;
   time(&end);

  printf("Execution time %f\n", difftime(end, begin));
  return (0);
}

EDIT:

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int main() {

  struct timeval  tv;
  gettimeofday(&tv, NULL);

double begin =
  (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;


 sleep(2);

 gettimeofday(&tv, NULL);

double end =
  (tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ;

  printf("Execution time %f\n", end - begin);
  return (0);
}