josephsherratt
Posts: 2
Joined: Fri Jun 20, 2014 10:26 pm

Time passed in microseconds

Fri Jun 20, 2014 10:39 pm

I am trying to write a code to measure the distance using a HC-SR04 module in C on my PI. I am struggling to measure the time taken in microseconds such as:

start_time = time_in_microseconds

*code*

end_time = time_in_microseconds

Any help would be much appreciated. Thanks

User avatar
AndyD
Posts: 2334
Joined: Sat Jan 21, 2012 8:13 am
Location: Melbourne, Australia
Contact: Website

Re: Time passed in microseconds

Fri Jun 20, 2014 11:28 pm

Use gettimeofday(), it measures time in microseconds. This code is just an example. Put the code you are trying to time between the two calls to gettimeofday(). Use timersub() to get the difference.

Code: Select all

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

int main(void)
{
    struct timeval start;
    struct timeval end;
    struct timeval total;

    gettimeofday(&start, NULL);
    sleep(3);
    gettimeofday(&end, NULL);
    timersub(&end, &start, &total);

    printf("time taken: %d.%06d\n", total.tv_sec, total.tv_usec);
    return 0;
}
The call to sleep(3) is just an example to give something to time.

josephsherratt
Posts: 2
Joined: Fri Jun 20, 2014 10:26 pm

Re: Time passed in microseconds

Sat Jun 21, 2014 7:24 pm

Thanks a lot! Works perfect

Return to “C/C++”