Using gettimeofday() To Measure Performance

This might not be the most optimal way, I'm sure there is a better way, but at least for what I'm doing I need to use the function gettimeofday() to measure execution time of a small section of code.

I've read the manual, and all other documentation that I can find, but apparently I'm just having a bad evening. So, I need to do something like this:

gettimeofday(time1)
some code
does a few things
gettimeofday(time2)

Then I need to find the difference, in microseconds, of the two times so I can print them. Any help on how to do this would be greatly appreciated, I'm still rather new to C++ in the Linux environment.
I don't know about being accurate to microseconds, but I generally use clock():
1
2
3
4
5
6
7
8
9
10
11
12
#include <ctime>

int main()
{
    clock_t start, end;

    start = clock();
    // do stuff
    end = clock();

    std::cout << "Process took " << (double(end - start) / CLOCKS_PER_SEC) << seconds << '\n';
}

On my machine time() returns a result in microseconds, but I could not say if it is actually accurate to that degree.

http://cplusplus.com/reference/clibrary/ctime/clock/
Last edited on
Topic archived. No new replies allowed.