import std/[times, os]
proc fib(n: uint64): uint64 =
if n <= 1: return n
return fib(n - 1) + fib(n - 2)
let time = cpuTime()
echo fib(47)
echo "Time taken: ", cpuTime() - time
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>
static uint64_t fib(uint64_t n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
int main() {
time_t t1 = time(NULL);
uint64_t res = fib(47);
time_t t2 = time(NULL);
printf("%llu seconds\n", t2 - t1);
return 0;
}
I'm trying to learn C because i'm tired of the new buzz word "safe" that, like a virus(i would say even worse than the FAKE corona "virus"), has contamined the minds and hearts of all you professional programmers(i'm an amateur), and so i chose the most unsafe language that there is, C (Btw i love pointers, although i still don't understand them well and i don't know if i'll ever understand them ahaha). Anyway i tried to benchmark these 2 functions, one in C and one in Nim, a language that i like, but pls Araq stop with this safety thing, LIFE ITSELF IS NOT SAFE and that's the beauty of it and of the most unsafe language out there, C!! , Anyway i was surprised to know that the C version executes in ~17 seconds while the Nim one, with '-d:release' flag of course, in 7.something seconds. What kind of sorcery does your "safe" language do? If i remember well, when i was learning a bit about Nim i read that the compiler first spits out C code which is then compiled to native code. Well, i used the same compiler for the C and Nim version, so how can C be so much slower than the Nim version? Anybody knows?Nim code is easier to analyze for the C compiler so the C compiler has an easier time doing constant folding and precomputing fibonacci .
Besides that, it's also possible that the compiled code has (by a stroke of luck) better alignment:
Or have link order interfere with benchmark:
You should mention that you already posted this question on Stackoverflow:
It has already been pointed out there that your environment (Mingw, Windows, gcc 8.10, different CPU, etc.) is not directly comparable to the results published in the repo (Linux/docker, gcc 9.3.0, etc.).