I tried calculating function executing time in C++ using methods from this page . Here's my code:
#include <bits/stdc++.h>
#include <sys/time.h>
#include <chrono>
using namespace std;
void myFunc(int a){
for(int i=0;i<1000000;i++){
a+=1;
}
}
int main(){
int a = 0;
time_t start1,end1;
time(&start1);
ios_base::sync_with_stdio(false);
myFunc(a);
time(&end1);
cout<<fixed<<double(end1-start1)<<setprecision(5)<<endl;
clock_t start2, end2;
start2 = clock();
mtFunc(a);
end2 = clock();
cout<<fixed<<double(end2-start2)<<setprecision(5)<<endl;
struct timeval start3, end3;
gettimeofday(&start3, NULL);
ios_base::sync_with_stdio(false);
myFunc(a);
Gettimeofday(&end3, NULL);
cout<<fixed<<double((end3.tv_sec - start3.tv_sec) * 1e6 + (end3.tv_usec - start3.tv_usec)) * 1e-6)<<setprecision(5)<<endl;
struct timespec start4, end4;
clock_gettime(CLOCK_MONOTONIC, &start4);
ios_base::sync_with_stdio(false);
myFunc(a);
clock_gettime(CLOCK_MONOTONIC, &end4);
cout<<fixed<<double((end4.tv_sec - start4.tv_sec) * 1e9 + (end4.tv_nsec - start4.tv_nsec)) * 1e-9)<<setprecision(5)<<endl;
auto start5 = chrono::high_resolution_clock::now();
ios_base::sync_with_stdio(false);
myFunc(a);
auto end5 = chrono::high_resolution_clock::now();
cout<<fixed<<chrono::duration_cast<chrono::nanoseconds>(end5 - start5).count()<<setprecision(9)<<endl;
return 0;
}
All methods prints 0.000000. Tried many times and it didn't changed. I also tried the solution from this answer but still not working. What's wrong here?
EDIT
I've read some comments and find out that myFunc()
doesn't do anything so the compiler optimizes it. So I write a new myFunc()
as below:
int myFunc(){
int a = 0;
for(int i=0;i<1000000;i++){
a+=1;
}
return a;
}
And I changed the calling of function as: int temp = myFunc();
.
Suprisingly still nothing worked.