Ok, so I was able to get the Nim and C++ examples to compile when using the 
heap (rather than the stack).

Comparing the code, I think the difference in performance is caused by two 
things:
    

  * The Nim code isn't in a main procedure
  * The C++ code is using int`s (32 bits) while Nim is using `int`s (64 bits). 
Nim's `int type is always the size of a pointer, so you can use it for indexing 
arrays.



The time I got for the modified code was about the same: 
    
    
    /tmp $>time ./temp
    result: 19999998
    
    real        0m0.847s
    user        0m0.792s
    sys 0m0.048s
    
    /tmp $>time ./temp_cpp
    result: 19999998
    
    real        0m0.905s
    user        0m0.851s
    sys 0m0.051s
    
    
    Run

And the code I used: 
    
    
    ## compiled with: nim -d:r c filename
    ## nim v 0.19.9
    
    proc main =
      const N = 20_000_000
      var data = newSeqUninitialized[int](N)
      # custom init
      for i in 0 ..< N:
        data[i] = i
      # busy work
      for r in 1 .. 50:
        for i in 3 ..< N-1:
          data[i] = (data[i+1]-data[i])+data[i-1]
      echo "result: ",data[N-2]
    
    main()
    
    
    Run
    
    
    // compiled with: c++ -O3 -o filename filename.cpp
    #include <iostream>
    const int N = 20000000;
    int main()
    {
      size_t* data = new size_t[N];
      // custom init
      for (size_t i=0; i<N; i++) {
        data[i] = i;
      }
      // busy work
      for (size_t r=0; r<50; r++) {
        for (size_t i=3; i<N-1; i++)
        {
          data[i] = (data[i+1]+data[i-1]) / 2;
        }
      }
      std::cout << "result: " << data[N-2] << std::endl;
      return ( 0 );
    }
    
    
    Run

Reply via email to