I wrote an application with Nim and discovered that an application with the 
same logic and data structures written in Python has a better execution speed 
than the Nim version.

I was trying to find out about the reason why Nim has a larger execution speed 
than Python. I isolated some code and tested two small and equivalent Python 
and Nim programs.

For a loop count of 100000 Python takes 1.0 sec and Nim takes 1.8 sec This 
speed ratio corresponds to the speed ratio in the real application.

I use Python version 2.7.3 and Nim compiler version 0.13.0 I compiled Nim with 
with -d:release option.

I'd like to know what is the reason why in this case Python beats Nim in 
execution speed.

Here are the both programs. The problem is the proc "do_something"
    
    
    # Nim example to test execution speed against a Python version
    import times, os
    
    var board: seq[char] = @['0', 'p', '.', 'p', 'P', '.', 'p', 'P', '.', 'p', 
'.', 'p', 'P', '.', 'p']
    const NE: seq[int] = @[8, 2, 13, 4, 5, 7, 8, 3, 9, 12, 7, 8, 3, 9, 12]
    const Directions = [NE, NE, NE, NE]  # for short: in real application the 
array elements differ
    
    proc do_something(board: seq[char]): seq[char] =
       var res: seq[char] = @[]
       for i, p in board:
          for d in Directions:
             res.add board[d[i]]
       return res
    
    let t0 = cpuTime()
    var res: seq[char]
    let count = 100000
    for i in 1..count:
       res = do_something(board)
    let t1 =  cpuTime()
    echo "***** Time elapsed for Nim: ", $(t1 - t0), "  Counts: ", $count
    ##echo res.repr
    
    
    
    
    # Python example to test execution speed against a Nim version
    import time, sys
    
    board = ['0', 'p', '.', 'p', 'P', '.', 'p', 'P', '.', 'p', '.', 'p', 'P', 
'.', 'p']
    NE = [8, 2, 13, 4, 5, 7, 8, 3, 9, 12, 7, 8, 3, 9, 12]
    directions = [NE, NE, NE, NE]  # for short: in real application the array 
elements differ
    
    def do_something(board):
       res = []
       for i, p in enumerate(board):
          for d in directions:
             res.append(board[d[i]])
       return res
    
    t0 =  time.time()
    res = []
    count = 100000
    for i in range(1, count):
       res = do_something(board)
    t1 =   time.time()
    print("***** Time elapsed for Python: ", str(t1 - t0)), " Counts: ", 
str(count)
    ##print res
    
    

Reply via email to