gpt4 book ai didi

c++ - 奇怪的 Visual Studio 行为 : Very long execution time

转载 作者:行者123 更新时间:2023-11-28 06:26:29 25 4
gpt4 key购买 nike

我注意到有些代码在 Visual Studio 中执行需要很长时间,而不是使用 CL 手动编译并运行可执行文件。

下面是展示此行为的代码示例:

int DP[MAX][MAX];
class CartInSupermarketEasy {
public:
int calc(int N, int K) {
clock_t begin = clock();
for (int i = 0; i < MAX; ++i) {
DP[0][i] = 0;
DP[1][i] = 1;
DP[i][0] = i;
}

for (int n = 1; n <= N; ++n) {
for (int k = 0; k <= K; ++k) {
int min_res = N;
for (int i = 1; i < n; ++i) {
for (int j = 0; j < k; ++j) {
int curr_res = max(DP[n - i][k - 1 - j], DP[i][j]) + 1;
min_res = min(curr_res, min_res);
}
}
DP[n][k] = min(min_res, DP[n - 1][k] + 1);
}
}
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
cout << elapsed_secs << '\n';
return DP[N][K];
}
} CI;

int main(){
cout << CI.calc(100,100) << '\n';
return 0;
}

在 VS2013 中运行时,函数 calc 计算答案大约需要 13.5 秒。在 VS2012 中,这下降到 3.5 秒。但是,当使用 CL(或我试过的任何其他编译器)手动编译时,可执行文件会在 0.4 秒内返回答案。

如何解释这种差异,以及如何使 VS 的执行与手动编译/执行相提并论?

谢谢。

最佳答案

问题是我正在使用“调试”配置而不是“发布”配置运行。将构建配置更改为“发布”已解决问题。有趣的是,它现在的运行速度比手动编译/执行快约 4 倍。

更新:正如评论中指出的那样,很多减速是由于使用 std::min 和 std::max 函数造成的。切换到定制的最小/最大函数,将执行速度提高了 3-4 倍。这是一篇证实这一观察的文章:std::min causing three times slowdown

关于c++ - 奇怪的 Visual Studio 行为 : Very long execution time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com