Seqs in nim have value type semantics. Your inner loop ( for d in Directions) 
actually assigns Directions[...] to d on every iteration which involves full 
copy of the seq. Here's the patched version. I have also preallocated result 
seq. 
    
    
    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: openarray[char]): seq[char] =
      result = newSeq[char](board.len * Directions.len)
      var ir = 0
      for i, p in board:
         for d in 0 ..< Directions.len:
            result[ir] = board[Directions[d][i]]
            inc ir
    
    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
    

Reply via email to