简体   繁体   中英

Python vs Javascript execution time

I tried solving Maximum Subarray using both Javascript(Node.js) and Python, with brute force algorithm. Here's my code:

Using python:

from datetime import datetime
from random import randint

arr = [randint(-1000,1000) for i in range(1000)]

def bruteForce(a):
  l = len(a)
  max = 0
  for i in range(l):
    sum = 0
    for j in range(i, l):
      sum += a[j]
      if(sum > max):
        max = sum
  return max

start = datetime.now()
bruteForce(arr)
end = datetime.now()

print(format(end-start))

And Javascript:

function randInt(start, end) {
    return Math.floor(Math.random() * (end - start + 1))
}

var arr = Array(1000).fill(randInt(-1000, 1000))

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)
        }
    }
    return max
}

var start = performance.now()
bruteForce(arr)
var end = performance.now()
console.log(end - start)

Javascript got a result of about 0.187 seconds, while python got 4.75s - about 25 times slower. Does my code not optimized or python is really that slower than javascript?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM