c++ - 如何修复程序上的错误以衡量性能

标签 c++ performance time clock

我想衡量有关矩阵乘法的代码的性能。

虽然我能够执行一个简单的程序并得到正确的答案,但我想要得到结果的程序却无法成功编译。

我该如何修复这些错误?

我尝试执行下面的简单程序来理解 C++ 中时间测量的基础。

输出

3seconds
#include <chrono>
#include <iostream>
#include <thread>

using namespace std::chrono;

int main()
{
  // 1. current date and time
  high_resolution_clock::time_point begin = high_resolution_clock::now();

  // 2. process to take time
  std::this_thread::sleep_for(seconds(3));

  // 3. current date and time 
  high_resolution_clock::time_point end = high_resolution_clock::now();

  // aquired passed time
  seconds elapsed_time = duration_cast<seconds>(end - begin);
  std::cout << elapsed_time.count() << "seconds" << std::endl;
}
#include <chrono>
#include <iostream>
#include <thread>

using namespace std::chrono;

int main()
{
    #define N 2

    double A[N][N] = {
        {1.0, 2.0},
        {2.0, 1.0}
    };

    double B[N][N] = {
        {3.0, 1.0},
        {0.0, 3.0}
    };

    double C[N][N] = {
        {0.0, 0.0},
        {0.0, 0.0}
    };
    int i, j, k;

    for(i=0; i<N; i++)
        for(j=0; j<N; j++)
            for(k=0; k<N; k++)
                C[i][j] += A[i][k]*B[k][j];


  // aquire the passed time
  seconds elapsed_time = duration_cast<seconds>(end - begin);
  std::cout << elapsed_time.count() << "seconds" << std::endl;
}
$ g++ -o clock clock.cpp
clock.cpp:34:49: error: use of undeclared identifier 'end'
  seconds elapsed_time = duration_cast<seconds>(end - begin);
                                                ^
clock.cpp:34:55: error: use of undeclared identifier 'begin'
  seconds elapsed_time = duration_cast<seconds>(end - begin);
                                                      ^
2 errors generated.

最佳答案

您忘记声明和初始化beginend

尝试:

#include <chrono>
#include <iostream>
#include <thread>

using namespace std::chrono;

int main()
{
    #define N 2

    // being
    high_resolution_clock::time_point begin = high_resolution_clock::now();



    double A[N][N] = {
        {1.0, 2.0},
        {2.0, 1.0}
    };

    double B[N][N] = {
        {3.0, 1.0},
        {0.0, 3.0}
    };

    double C[N][N] = {
        {0.0, 0.0},
        {0.0, 0.0}
    };
    int i, j, k;

    for(i=0; i<N; i++)
        for(j=0; j<N; j++)
            for(k=0; k<N; k++)
                C[i][j] += A[i][k]*B[k][j];


    // end
    high_resolution_clock::time_point end = high_resolution_clock::now();


  // aquire the passed time
  seconds elapsed_time = duration_cast<seconds>(end - begin);
  std::cout << elapsed_time.count() << "seconds" << std::endl;
}

关于c++ - 如何修复程序上的错误以衡量性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57181427/

相关文章:

c++ - 如何访问 C++ 中其他文件中的静态链接变量?

javascript - 使用 Javascript 将数据存储在大型数组中时的性能问题

datetime - 将每小时数据汇总为每日汇总

linux - Bash 计算执行时间

c++ - C++中 "free function"这个词是什么意思?

C++ - 返回 bool 值然后验证它

c++ - 随机 float 生成

c++ - 使用 QHash 和 QList 提高性能

python - 寻找良好的索引和稀疏矩阵方法以从现有矩阵创建矩阵

Java:java.util.date 无法转换为 java.sql.Time