VS 2017 和 2019 运行 c++ 真的很慢
VS 2017 & 2019 run c++ really slow
我从python的小程序开始,但运行它需要很长时间,所以我切换到c ++。我没有这种特定语言的早期经验(尽管用 c# 编码了很多(,并且从 Web 编辑器开始:https://www.onlinegdb.com/online_c++_compiler。
我的C++代码是:
clock_t start, end;
/* Recording the starting clock tick.*/
start = clock();
int R = 0;
int x = 0;
for (R = 6; R <= 10000; R = R + 2) {
int X_min = ceil(0.5 * sqrt(2) * R);
int N_pairs = 0;
for (x = X_min; x < R; x++) {
float y = sqrt(pow(R, 2) - pow(x, 2));
if (rint(y) == y) {
N_pairs = N_pairs + 1;
}
}
if (N_pairs >= 4) {
//cout << R << ", " << N_pairs;
//cout << "n";
}
}
end = clock();
//Calculating total time taken by the program.
double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
cout << "Time taken by program is : " << time_taken;
cout << " sec " << endl;
//cout << "1" << "|" << "2" << "|" << "3 n";
//cout << "4" << "|" << "5" << "|" << "6 n";
//cout << "7" << "|" << "8" << "|" << "9 n";
一切都运行良好,但是Web编辑器似乎有一个内置的最大时间边界,所以在这一点上我决定把它带到Visual Studio。
我复制粘贴的代码并运行它:
- Web 编辑器花了 0.272273 秒来完成代码
- Visual Studio花了2.446秒来运行它。
我尝试将VS从2017版本更新到2019版本,但没有效果。
为什么VS运行代码需要这么长时间??我该如何解决它?
主要问题是 VC++ 不内联rint(float)
调用:
movaps xmm0, xmm6
call rint
ucomisd xmm0, xmm6
链接到 Godbolt
您可以通过将rint(y)
替换为"手动"舍入来期待良好的加速:
改变
if (rint(y) == y) {
自
if (int(y+0.5) == y) {
在我的机器上从0.8 秒下降到0.04 秒(用/O2 /fp:fast
编译(
此外,您需要在循环外使用N_pairs
否则(好的(编译器可以优化所有内容。
优化的第一条规则:不正确程序的性能无关紧要。
看来您正在寻找x^2 + y^2 = R^2
的整数解。但是,将float
数据类型用于中间存储会产生大量误报。将N_pairs
移出循环(以防止完全删除该循环,如@rustyx所述,并计算所有对(结果为 7886 对;double
:5681。
最后一个数字也对应于完全整数检查,这要快得多(在我的系统上为 21 毫秒(。这是我的代码:
#include <iostream>
#include <chrono>
int main()
{
auto t = std::chrono::high_resolution_clock::now();
int N_pairs = 0;
double d = 0.5 * sqrt(2);
for (int R = 6; R <= 10000; R = R + 2) {
int X_min = ceil(d * R);
for (int x = X_min; x < R; x++) {
int y = sqrtf(R * R - x * x);
if(x*x + y*y == R*R) {
N_pairs = N_pairs + 1;
}
}
}
std::cout << "Time taken by program is: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - t).count()
<< " ms" << std::endl;
std::cout << "N_pairs: " << N_pairs << std::endl; // with float: 7886; with double or int: 5681
return 0;
}
相关文章:
- 在决定是通过参考还是通过价值时,尺寸真的是一个问题吗
- 字节真的是最小可寻址单元吗
- 如果我真的真的想从 STL 容器继承,并且我继承构造函数并删除新运算符,会发生什么?
- 如何在 std::vector 中找到<bool>哪些索引是真的?
- std::string 的对象真的可以移动吗?
- 在这种情况下,我真的复制了字节还是复制了字符?
- int8_t和uint8_t真的是整数吗?它们有什么用?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 查找不等式为真的次数时出现问题
- 考虑到其他好处,关键字'auto'真的有助于简化调试C++吗?
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 在为嵌套类定义行外友元时,我真的必须打破封装吗?
- 你如何理解"std: :forward is just syntactic sugar"?这是真的吗?
- "std::forward"和"std::move"真的不生成代码吗?
- VS 2017 和 2019 运行 c++ 真的很慢
- 结构和类在C++中真的等价吗?
- 指向数组unique_ptr在调用 release() 后会自动释放动态内存,这是真的吗?
- 运算符重载是否真的需要返回值C++?
- 我想使用 "cout" 命令慢慢打印文本,但我真的找不到任何解决方案
- " sizeof "操作员在编程中真的很重要吗,尤其是在构建大型应用程序时?