Why this code is taking 3.87 seconds in C++?
#include <stdio.h>
#include <time.h>
int main() {
int iterations=999999;
int size=1000;
int i,k;
clock_t tStart = clock();
for (k=0;k<iterations;k++){
for(i=0; i<size; i++){
//ANYTHING (the content is not important)
}
}
printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC);
return 0;
}
I am using it on Eclipse on Ubuntu 16. This is the command that Eclipse is using to compile it:
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"src/myexample.d" -MT"src/myexample.o" -o "src/myexample.o" "../src/myexample.cpp"
I tried the same code on Java and it takes only 0.006 seconds.
What am I doing wrong?
Thank you!
EDIT
Sorry I didn't want to say that Java is better than C++. I just expected a better result in C++ and I wanted to know why I was obtaining a bad performance, so I tried the same code in Java.
SOLVED
Using -O3 I get miliseconds.
EDITED AGAIN
Yes, I know that is a nested loop, but don't worry about that. I know what I am doing (the code was simplified to formulate the question, it is much more complex in the full version). The error was in the compiler command. Read @chqrlie answer.
Thank you!