首页 > 解决方案 > time() 函数在 Microsoft C++ 中运行缓慢

问题描述

我偶然发现 C++time()函数在使用 Microsoft C++ 编译的程序中运行缓慢。考虑这个例子:

#include <iostream>
#include <ctime>

long long unsigned Fib(unsigned n)
{
  if (n <= 2)
    return 1;
  else
    return Fib(n-1) + Fib(n-2);
}

int main(int argc, char* argv[])
{
  time_t start_time = time(NULL);

  // Calculate the first 50 Fibonnaci numbers
  for (unsigned i = 1; i <= 50; i++)
    std::cout << i << "\t" << Fib(i) << "\t" << difftime(time(NULL), start_time) << std::endl;

// This takes 105 seconds to run, but the last line printed is:
// 50      12586269025     65

  return 0;
}

这打印:

1       1       0
2       1       0
...
49      7778742049      40
50      12586269025     65

所以difftime(time(NULL), start_time)告诉我它需要 65 秒才能运行,但是当我用秒表计时时,我发现它实际上需要 105 秒。

问题是该time()函数返回运行缓慢的时间。如果我time(NULL)直接打印而不是调用,difftime()我可以看到打印的时间落后于实际时间。例如,如果我在程序完成时打印time()而不是difftime()然后立即重新运行它,我发现当我再次运行程序时时间会向前跳跃:

49      7778742049      1611148562
50      12586269025     1611148587

D:\rhs\c>test
1       1       1611148627
2       1       1611148627

请注意返回的值是如何time()向前跳转 40 秒的,即使我只花了一秒钟来重新运行程序。

所以我的问题是为什么会发生这种情况以及如何解决它(除了使用不同的编译器 - 我别无选择,只能使用 MS C++)?我正在使用 Visual Studio 2019,因此 C++ 编译器的版本是Microsoft (R) C/C++ Optimizing Compiler Version 19.28.29335 for x86


啊,好尴尬啊,确实只是cout陈述中的评价顺序。如果我将循环更改为:

  for (unsigned i = 1; i <= 50; i++)
  {
    long long unsigned u = Fib(i);
    double run_time = difftime(time(NULL), start_time);
    std::cout << i << "\t" << u << "\t" << run_time << std::endl;
  }

然后它打印正确的经过时间。感谢所有评论的人。这可以作为副本关闭。

标签: c++time

解决方案


推荐阅读