找到测试的最小值和最大值

时间:2018-03-22 20:32:07

标签: c++ visual-c++

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

离。

0 min = 0 max = 155

1 min = 0 max = 155

1 min = 0 max = 155

2 min = 0 max = 155

3 min = 0 max = 155

5 min = 0 max = 155

8 min = 0 max = 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;
}

1 个答案:

答案 0 :(得分:0)

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

根据评论中的建议使用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;
}