r/nim • u/[deleted] • Jan 08 '22
Nim's while loops 7x slower than Python?
I found something strange when messing around with while loops, my Python program can do about 7x the iterations of Nim in 1 second:
Python 3.10.1
import time
currentTime = time.time()
interval = 1
count = 0
while time.time() - currentTime < interval:
count += 1
print(count)Output: 5 513 863
Nim 1.6.2
import std/times
let currentTime = now()
let interval = initDuration(seconds = 1)
var count: int = 0
while now() - currentTime < interval:
count += 1
echo countOutput: 799 346
C++ (gcc 11.2.0)
#include <iostream>
int main() {
auto currentTime{time(NULL)};
int count{};
int interval{1};
while (time(NULL) - currentTime < interval)
count++;
std::cout << count;
}Output: 412 992 387
Am I doing something wrong?
8
Jan 08 '22
First of all, you're not actually comparing the performance of while loops - you're comparing the performance of time functions.
That said, try compiling the Nim version with -d:release or even -d:danger if you haven't already - even the compiler tells you that the debug build is slow (unless you disabled hints).
But yeah, this is not representative of real world performance at all, Nim while loops are the same "speed" as C/C++ if you really want to compare their performance.
3
u/TheDarkMode Jan 08 '22
There is a reason why they say don't benchmark small samples, and I think you found out why
2
u/TheDarkMode Jan 08 '22
Follow Up Question:
Since Nim is compiled to C, I would of thought it's time module, would of been based off C. Yet in the above example the Cpp is still faster then the Nim implementation, is that because Nim has extra functionality and it is a trade off from Speed vs Usability?
Or is this a use case where using Cpp is better?
Food for thought
1
u/Familiar_Ad_8919 Jan 08 '22
try
powershell -Command "Measure-Command {path\to\your\file.exe}"
it gives a more realistic measure
15
u/haxscramper Jan 08 '22
std/times.now()returnsDateTimeobject which you then subtract from, then compare. The object itself is quite big https://nim-lang.org/0.20.0/times.html#DateTime and surely has much higher overhead compared to thetime()function from C that returns integer. I would imagine python time handling logic has a lower overhead as well.So in short, you are benchmarking time object handling speed, and not the loop itself.
count++overhead is negligible in this benchmark.You need to exclude anything besides
countincrements and integer compares from the loop - I would imaginetime()/now()/time.time()does a lot of system calls etc. Instead, compare how long does it take to count to a billion, for example.