Here's the program:
timer.cpp:
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
#include <time.h>
int main( int argc, char** argv) {
#define BILLION 1E9
struct timespec requestStart, requestEnd;
// Calculate time taken by a request
clock_gettime(CLOCK_REALTIME, &requestStart);
//function_call(); // time this
clock_gettime(CLOCK_REALTIME, &requestEnd);
// Calculate time it took
double accum = ( requestEnd.tv_sec - requestStart.tv_sec )
+ (( requestEnd.tv_nsec - requestStart.tv_nsec ) / BILLION);
cout << accum << endl;
}
On Mac OSX 10.8.5 I have access to two compilers: Apple LLVM version 4.2 (clang-425.0.28), invoked as c++
, and gcc version 4.2.1 (wow, that's old), invoked as g++
.
c++ timer.cpp:
error: use of undeclared identifier 'CLOCK_REALTIME'
clock_gettime(CLOCK_REALTIME, &requestStart);
g++ timer.cpp:
timer.cpp: In function ‘int main(int, char**)’:
timer.cpp:15: error: ‘CLOCK_REALTIME’ was not declared in this scope
timer.cpp:15: error: ‘clock_gettime’ was not declared in this scope
Am I omitting anything, or am I simply working with archaic compilers?
UPDATE I've verified that this solution works with the stock c++ and g++ compilers and libraries on OSX 10.8.5.