Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
分析一个C++;使用高分辨率时钟编程 我想对我的C++程序进行配置,并为此目的而使用。作为示例,提供了一个关于该问题的示例代码。我试过三种不同的方法_C++_Profiling - Fatal编程技术网

分析一个C++;使用高分辨率时钟编程 我想对我的C++程序进行配置,并为此目的而使用。作为示例,提供了一个关于该问题的示例代码。我试过三种不同的方法

分析一个C++;使用高分辨率时钟编程 我想对我的C++程序进行配置,并为此目的而使用。作为示例,提供了一个关于该问题的示例代码。我试过三种不同的方法,c++,profiling,C++,Profiling,示例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_reso

示例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;
}
这显示了
3792420263
微秒,我对此也表示怀疑


例2和例3的问题是什么。三个选项中哪一个是正确的

编译器会优化这些循环。如果您在选项菜单中禁用优化,它将显示合理的值。

示例2由编译器优化,因此如果您想查看循环运行时,应该禁用任何编译器优化

示例3毫无意义,因为您在每个循环中添加了一个不同的时间,而结果是一个与循环运行时间无关的数字。此外,在使用32位
无符号int-ttime
的循环过程中,会遇到许多溢出

因此,分析真实代码的最佳解决方案是示例2。不要担心您的零输出,如果您在
t1
t2
创建之间添加任何“合理代码”,您将得到更好的数字

#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;
}
#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;
}