performance - c++,cin 有问题吗?

标签 performance c++11 testing cmath

<分区>

我写了一个小测试来找出对特殊 x 最快的数学运算。我想让用户输入 x,这样我就可以针对不同的 x 运行测试。在下面的代码中,我告诉我 std::cin >> val; 有错误 错误:无法将“std::istream {aka std::basic_istream}”左值绑定(bind)到“std::basic_istream&&”

如果我将 val 声明为 double val 而不是 const double val 我会得到更多错误。我可以更改什么以使程序运行?

#include <cmath>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <istream>
#include <ostream>
// for x^1.5 
double test_pow_15(double x) { return std::pow(x, 1.5); };
double test_chain_15(double x) { return sqrt(x * x * x); };
double test_tmp_15(double x) { double tmp = x * x * x; return sqrt(tmp); };


volatile double sink;
const double val = 0;
const double ans_15 = std::pow(val, 1.5);

void do_test(const char* name, double(&fn)(double), const double ans) {
    auto start = std::chrono::high_resolution_clock::now();
    for (size_t n = 0; n < 1000 * 1000 * 10; ++n) {
        sink = val;
        sink = fn(sink);
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> dur = end - start;
    std::cout << name << ".Took" << dur.count() << "ms, error:" << sink - ans << '\n';
}

int main()
{
    std::cout << "Speed test"<< '\n';
    std::cout << "Please enter value for x."<< '\n';
    std::cout << "x = ";
    std::cin >> val;

    std::cout << "Speed test starts for x = "<< val <<"."<<'\n';
    std::cout << " " << '\n';
    std::cout << "For " << val<<"^(1.5) the speed is:" <<'\n';
    do_test("std::pow(x,1.5)                                  ",test_pow_15, ans_15);
    do_test("sqrt(x*x*x)                                      ",test_chain_15, ans_15);
    do_test("tmp = x*x*x; sqrt(tmp)                           ",test_tmp_15, ans_15);

    return 0;
}

最佳答案

我认为如果您删除“const”关键字,它可能会正常工作。

double val = 0;

关于performance - c++,cin 有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58391275/

相关文章:

java - Python 代码的运行速度比 Java 慢 20 倍。有没有办法加速Python?

c++ - 运行时绑定(bind)和模板实例化

c++ - constexpr 函数参数作为模板参数

c# - 如何欺骗windows浏览对话框?

c# - 编译委托(delegate)表达式的性能

ASP.NET、IIS/CLR 线程和请求与同步与异步编程的关系

performance - 是什么让 Everything 的文件搜索和索引如此高效?

c++ - 删除重载函数。 C++11。重载的调用......是模棱两可的

ruby-on-rails - 在 View 中使用另一个模型导致测试错误

unit-testing - 如何在 retryAnalyzer 后将 TestNG DefaultSuite 结果发送到 Maven Surefire 插件