I am trying to measure the running time of a function using clock_gettime()
. I am including time.h
, I added -lrt
to the Makefile, and added the right path on Eclipse CDT. However, when I try to compile I keep getting these kinds of errors:
experiments.c: In function ‘main’:
experiments.c:137:2: error: unknown type name ‘timespec’
timespec time1, time2;
^
experiments.c:139:2: warning: implicit declaration of function ‘clock_gettime’ [-Wimplicit-function-declaration]
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
^
experiments.c:139:16: error: ‘CLOCK_PROCESS_CPUTIME_ID’ undeclared
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
This happens with any type of CLOCK_
I try to use. I've been reading plenty of questions/answers and tutorials but haven't been able to find something that helps.
The headers I'm including are:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <time.h>
I'm on Ubuntu 13.10 32 bit and compiling on gcc
with the following CFLAGS
: -g -Wall -pedantic -std=c99
If I add the flag -D_POSIX_C_SOURCE=199309L
I get error: unknown type name ‘timespec’
and warnings about using timespec
.
This is the part of the code, just in case it helps:
timespec time1, time2;
int temp;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
.
.
.
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
/*code stuff*/
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time2);
Thanks
Putting this and this answers together I was able to make it work. I had to add the _POSIX_C_SOURCE
macro, to make sure the preprocessor was getting the library features correctly, which I did by adding this line before all my includes:
#define _POSIX_C_SOURCE 199309L
Then I started getting a unknown type name timespec
error, which was happening because you have to tell the compiler explicitly that timespec
is a struct
. Fixed it by writing:
struct timespec time1, time2;
instead of just timespec time1, time2;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With