代码示例

  • c++ 示例
#include <iostream>
#include <iomanip>
#include <chrono>

long fibonacci(unsigned n)
{
    if (n < 2) return n;
    
    return fibonacci(n - 1) + fibonacci(n - 2);
}

int main()
{
    std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
    
    unsigned n = 20;
    std::cout << n << " fibonacci numbers are:" << std::endl;
    for (unsigned i = 1; i <= n; i++)
    {
        long result = fibonacci(i);
        std::cout << result << " ";
    }
    
    std::cout << std::endl;
    
    const auto end = std::chrono::steady_clock::now();
    const std::chrono::duration<double> elapsedSeconds = end - start;
    
    /// after c++20, operator<<duration is ok
    std::cout << "elapsed seconds:" << std::fixed << std::setprecision(10) << elapsedSeconds.count() << "s" << std::endl;

    return 0;
}
  • 执行结果
20 fibonacci numbers are:
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 
elapsed seconds:0.0002522690s

参考

08-25 23:13