Python is not per se slower than Javascript, it depends on the implementation.
Here the results comparing node and PyPy which also uses JIT:
> /pypy39/python brute.py
109.8594 ms N= 10000 result= 73682
> node brute.js
167.4442000091076 ms N= 10000 result= 67495
So we could even say "python is somewhat faster" ...
And if we use Cython, with a few type-hints, it will be again a lot faster - actual full C speed:
> cythonize -a -i brutec.pyx
> python -c "import brutec"
69.28919999999998 ms N= 10000 result= 52040
To make the comparison reasonable, I fixed a few issues in your scripts:
- Fix: the js script filled an array with all the same values from a single random
- Does the same basic kind of looping in Python - instead of using the range iterator (otherwise its a little slower)
- Use the same time format and increase the array length to 10000 - otherwise the times are too small regarding resolution and thread switching jitter
Python code:
from time import perf_counter as clock
from random import randint
N = 10000
arr = [randint(-1000,1000) for i in range(N)]
def bruteForce(a):
l = len(a)
max = 0
i = 0
while i < l:
sum = 0
j = i
while j < l:
sum += a[j]
if sum > max:
max = sum
j += 1
i += 1
return max
start = clock()
r = bruteForce(arr)
end = clock()
print((end - start) * 1000, 'ms', 'N=', N, 'result=', r)
##print(arr[:10])
JS code:
var start = -1000, end = 1000, N=10000
var arr = Array.from({length: N},
() => Math.floor(Math.random() * (end - start + 1) + start))
function bruteForce(arr) {
var max = 0
for (let i = 0; i < arr.length; i++) {
var sum = 0
for (let j = i; j < arr.length; j++) {
sum += arr[j];
max = Math.max(max, sum)
//~ if (sum > max) max = sum;
}
}
return max
}
var start = performance.now()
r = bruteForce(arr)
var end = performance.now()
console.log(end - start, 'ms', 'N=', N, 'result=', r)
//~ console.log(arr.slice(0, 10))
Code for Cython (or Python), enriched with a few type-hints:
import cython
from time import perf_counter as clock
from random import randint
N = 10000
arr = [randint(-1000,1000) for i in range(N)]
def bruteForce(arr):
l: cython.int = len(arr)
assert l <= 10000
a: cython.int[10000] = arr # copies mem from Python array
max: cython.int = 0
i: cython.int = 0
while i < l:
sum: cython.int = 0
j: cython.int = i
while j < l:
sum += a[j]
if sum > max:
max = sum
j += 1
i += 1
return max
start = clock()
r = bruteForce(arr)
end = clock()
print((end - start) * 1000, 'ms', 'N=', N, 'result=', r)
##print(arr[:10])
(Done on a slow notebook)