First the program took like 35 seconds to execute, but after some optimizations such as switching from python to cpp, it took about 0.3 seconds

  • 29
    Rewriting everything from scratch is my favorite optimization :D
  • 1
    I don't think you can gain that kind of performance boost by just switching langauge AFAIK even CPU bound process in c++ just provide 5x performance boost than python.
  • 3
    @-pthread Depends on specific case, I suppose, but I'd guess 10-15x achievable. Python's internal VM is rather rudimentary, it doesn't even apply trivial optimizations. On the other hand with C++ you're not only compiling to native code, but you also get compile-time optimizations. I'd expect that alone to give you 10x in some cases.
  • 1
    Can't python just be compiled into native code?
  • 1
    @OneOfSimpleMind nope, Python is entirely interpreted and cannot be compiled

    I thiiiiink there is something like Cpython or something like this which does some changes to it but idk don't quote me on that
  • 2
    @OneOfSimpleMind there are some tricks to that (mostly tools):

    Py2exe - literally just makes an executable that contains the python interpreter and the python source in one file. It's useful, but it's still interpreted. And the binaries are large.

    Pyinstaller - see above

    Nuikta - now we are talking! This is a python to c++ transpiler. Yes, it will compile to native machine code. No, it will not add much performance. The code it writes is machine generated. And is as good as you think machine generated code will be. ie oh my God is it unreadable.

    I like nuikta. A lot actually. But it is not a performance enhancement thing. It does not compile python. It converts python into very functional, but very ugly, and likely non-optimizable C++.
  • 0
    @deadPix3l i personally prefer pyinstaller. It's easy to use.
  • 3
    @OneOfSimpleMind your thinking of Cython.

    I can see a python script that runs in a second or so being rewritten in c++ to get sub second results, but if the original script took 35 seconds, there were other problems with that original script.
Add Comment