0

Why constexpr is not quickly showing result

I thought constexpr gives result very quickly and result computed at compilation only. Why below code even with constexpr runs slower and not quickly? https://sololearn.com/compiler-playground/cak5gac4YD2I/?ref=app

30th Jan 2025, 3:46 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
6 Antworten
+ 5
Ketan Lalcheta change line 7 from or <- to || <- You'll see you spent 0 milliseconds and the result suggestion: Use #include <chrono> // For timing
30th Jan 2025, 5:10 PM
BroFar
BroFar - avatar
+ 2
it will not be quick because you're measuring compile time. The compiler have to do the long calculations. Once you compiled the code into an optimized executable, that computed value will be stored as a constant value and will not have to be computed every time. Then it will be your quick result. C++ is supposed to be used in it's compiled form.
31st Jan 2025, 2:55 PM
Bob_Li
Bob_Li - avatar
+ 1
Ketan Lalcheta if I understand your code correctly (comments would help), you are using recursion to calculate nth number in Fibonacci sequence with added code to prevent duplicate recursion calls for the same nth number. Even with the added code, you are still looking at O(2^n) time complexity, i.e. exponential growth. So calculating 5000th term is going to take a LONG time.
30th Jan 2025, 4:51 PM
Shardis Wolfe
+ 1
BroFar sounds good to use chrono or benchmarking. However I could not get about or and || What makes a difference of using or keyword and ||
31st Jan 2025, 7:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Shardis Wolfe I don't think time complexity is exponential. It is only O(2N) and not exponential. State is saved in each computation into dp state and hence avoiding computation again and again for each number
31st Jan 2025, 7:07 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta || is more commonly used in c to c++ development while "or" was introduced as an alternative to be more English friendly in codes ... and may not always work as well or as truly intended. In short, || is machine friendly, as well as more developers recognized.
31st Jan 2025, 7:19 PM
BroFar
BroFar - avatar