Sujet : Re: constexpr is really very smart!
De : student (at) *nospam* invalid.invalid (Student Project)
Groupes : comp.lang.c++Date : 18. Dec 2024, 05:45:20
Autres entêtes
Organisation : To protect and to server
Message-ID : <vjtkcb$39cft$1@paganini.bofh.team>
References : 1 2
On 17/12/2024 20:20, Keith Thompson wrote:
Student Project <student@invalid.invalid> writes:
The constexpr is really very smart because it can speed up algorithms
1000 times according to Dave, Microsoft retired engineer. He has proved it
by creating this video:
>
<https://youtu.be/8-VZoXn8f9U?si=iy1UimoWcaLG31Xi>
>
On my computer it took 270 microseconds to calculate fib(35) like in his
example. It was almost instant at the blink of the eyes.
Can you post the relevant code?
[...]
Code in the boxed area below: (The purpose is to demonstrate constexpr NOT the recursive algorithm. The video is very clear about this).
It is the same code as in the video. G++ gives you the best result after
changing one line to:
/*constexpr*/ int result_c = fibonacci_c(num);
G++ result is (multiple runs) - All timings in milliseconds:
D:\CmdLine\C_Cpp\Chrono05>program
Fibonacci_c 9227465
Time taken: 9
Fibonacci 9227465
Time taken: 289
D:\CmdLine\C_Cpp\Chrono05>program
Fibonacci_c 9227465
Time taken: 4
Fibonacci 9227465
Time taken: 276
D:\CmdLine\C_Cpp\Chrono05>program
Fibonacci_c 9227465
Time taken: 8
Fibonacci 9227465
Time taken: 284
D:\CmdLine\C_Cpp\Chrono05>program
Fibonacci_c 9227465
Time taken: 5
Fibonacci 9227465
Time taken: 276
clang++ and Visual studio are the slowest. I don't know why.
<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>
#include <iostream>
#include <chrono>
int fibonacci(int n)
{
if (n <= 1)
return n;
return fibonacci(n - 2) + fibonacci(n - 1);
}
constexpr int fibonacci_c(int n)
{
if (n <= 1)
return n;
return fibonacci_c(n - 2) + fibonacci_c(n - 1);
}
int main(void)
{
// using namespace std::literals::chrono_literals;
auto start = std::chrono::high_resolution_clock::now();
constexpr int num = 35;
/*constexpr*/ int result_c = fibonacci_c(num);
std::cout << "Fibonacci_c " << result_c << "\n";
std::cout << "Time taken: " <<
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()
- start).count() << "\n";
start = std::chrono::high_resolution_clock::now();
int result = fibonacci(num);
std::cout << "Fibonacci " << result << "\n";
std::cout << "Time taken: " <<
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now()
- start).count() << "\n";
}
<+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++