我想剖析我的C++程序,並使用high_resolution_clock來達到此目的。這方面的示例代碼僅作爲示例提供。我嘗試了三種不同的方式。使用high_resolution_clock分析C++程序
實施例1
#include<iostream>
#include <chrono>
using namespace std;
using namespace chrono;
unsigned int ttime = 0;
int main(){
int i = 0;
int j = 0;
while(i < 10000000){
high_resolution_clock::time_point t1 = high_resolution_clock::now();
j += i;
i++;
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto tm_duration = duration_cast<microseconds>(t2 - t1).count();
ttime += tm_duration;
}
cout << "Took " << ttime << " microseconds " << endl;
return 0;
}
在循環內該example使用時鐘和效果良好,給出的結果如預期。
實施例2
#include<iostream>
#include <chrono>
using namespace std;
using namespace chrono;
unsigned int ttime = 0;
int main(){
int i = 0;
int j = 0;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
while(i < 10000000){
j += i;
i++;
}
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto tm_duration = duration_cast<microseconds>(t2 - t1).count();
ttime += tm_duration;
cout << "Took " << ttime << " microseconds " << endl;
return 0;
}
這example顯示0
時間,我懷疑的。
實施例3
#include<iostream>
#include <chrono>
using namespace std;
using namespace chrono;
unsigned int ttime = 0;
int main(){
int i = 0;
int j = 0;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
while(i < 10000000){
j += i;
i++;
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto tm_duration = duration_cast<microseconds>(t2 - t1).count();
ttime += tm_duration;
}
cout << "Took " << ttime << " microseconds " << endl;
return 0;
}
這example顯示3792420263
微秒我也懷疑。
example 2
和example 3
有什麼問題。哪三個是正確的。