I am a novice in nim, but want to use it to write functions to use in python. I am using nimpy
and nimporter
for importing nim functions to python.
This function in python:
def pcompare(a, b):
letters = []
for i, letter in enumerate(a):
if letter != b[i]:
letters.append(f'{letter}{i}{b[i]}')
return letters
Returns a list of cases where characters in string a
does not match characters in string b
.
I wrote the same functions in nim:
compare.nim
import strformat
import nimpy
proc compare(a, b: string): seq[string] {.exportpy.} =
for i, letter in a:
if letter != b[i]:
result.add(fmt"{letter}{i}{b[i]}")
Which i can import to python: import nimporter; import compare;
The functions generates the same output as the python code.
However, the nim function is much slower than the python code!
a = 'aaaa' * 1000000
b = 'bbba' * 1000000
s = time.perf_counter()
ptest = pcompare(a, b)
e = time.perf_counter()
print(e - s)
s = time.perf_counter()
ntest = compare.compare(a, b)
e = time.perf_counter()
print(e - s)
output:
python: 1.2781826159916818
nim: 3.607558835996315
Can anyone that is fluent in nim or another compiled language explain why this is the case, and perhaps suggest improvement to my nim code?
All comments are much appreciated!
Thanks, William