【问题标题】:Finding the min and max of a test查找测试的最小值和最大值
【发布时间】:2018-03-22 20:32:06
【问题描述】:

该程序仅打印出斐波那契数以及使用两种不同方法计算它们所花费的时间。在我重复时间测试 6 次后,我需要能够找到为每个数字计算它们所花费的时间的最大值和最小值。我知道如何重复六次我只是不知道如何从这 6 次测试中找到最小值和最大值。我认为我需要的是在 GetTickCount() 函数之前添加一个循环,然后在每次通过时使用 if 语句来比较测试。这是正确的还是我想错了?如果它是正确的,它是如何完成的?我尝试了几种不同的方法,但它最终为每个斐波那契数字打印了相同的数字。

例如

0 最小值 = 0 最大值 = 155

1 分钟 = 0 最大 = 155

1 分钟 = 0 最大 = 155

2 分钟 = 0 最大 = 155

3 分钟 = 0 最大 = 155

5 分钟 = 0 最大 = 155

8 分钟 = 0 最大 = 155

const int MAXN(45);

int main()
{
  unsigned long int before, after, diff, result;

  cout << "Execution time for Fibonacci no. implementions (ms)\n";
  cout << setfill('+') << setw(64) << "+" << endl << setfill(' ');
  cout << setw(4) << "n" << setw(30) << "Recursive"
  << setw(30) << "Iterative" << endl;
  cout << setfill('+') << setw(64) << "+" << endl << setfill(' ');
  for (int n=0; n<=MAXN; n++) {
    cout << setw(4) << n;

    before=GetTickCount();
    result=FiboRecursive(n);
    after=GetTickCount();

    diff=after-before;
    cout << setw(20) << result << setw(10) << diff;

    before=GetTickCount();
    result=FiboIterative(n);
    after=GetTickCount();

    diff=after-before;
    cout << setw(20) << result << setw(10) << diff;
    cout << endl;
  }
  return 0;
}

【问题讨论】:

  • GetTickCount 是一个非常糟糕的计时器。请改用chrono::high_resolution_clock
  • @MikeVine 我知道它是,但我的老师说我们必须使用它。

标签: c++ visual-c++


【解决方案1】:

是的,您只需遍历要测试的样本数量,然后检查结果。

按照 cmets 中的建议使用 chrono::high_resolution_clock

...

for (int n=0; n<=MAXN; n++) {

    double min = std::numeric_limits<double>::max();
    double max = 0;

    for (int i = 0; i < 6; ++i) {
        auto start = std::chrono::high_resolution_clock::now();
        result=FiboRecursive(n);
        auto end = std::chrono::high_resolution_clock::now();
        double duration = (end - start).count();
        min = std::min(min, duration);
        max = std::max(max, duration);
    }
}

编辑: 使用 GetTickCount():

for (int n=0; n<=MAXN; n++) {

    unsigned long int min = std::numeric_limits<unsigned long int >::max();
    unsigned long int max = 0;

    for (int i = 0; i < 6; ++i) {
        unsigned long int start = GetTickCount();
        result=FiboRecursive(n);
        unsigned long int end = GetTickCount();
        double duration = end - start;
        min = std::min(min, duration);
        max = std::max(max, duration);
    }

    std::cout << "For n: " << n << ", min: " << min << ", max: " << max;
}

【讨论】:

  • 感谢您的回答。我无法使用它,因为我必须为这个类使用 GetCountTik()。我刚刚建立了一个数组并将值放在那里,然后找到了该数组的最小值和最大值。
  • 如果你必须使用GetTickCount(),同样的事情,你只需要改变单位。我会更新答案。
猜你喜欢
  • 2012-09-16
  • 2017-04-20
  • 2019-02-25
  • 2021-09-15
  • 2014-06-17
  • 2013-09-28
  • 2019-09-16
  • 1970-01-01
相关资源
最近更新 更多