Hacker News
points by stefanos82 1 day ago | 0 comments
If you want to use the same code unmodified *and* your code uses type hints, then you should use mypyc [1].

There are times that it generates faster code than Cython! Of course with Cython you can tweak it and push its limits with various optimizations and other techniques, but for using your existing code as it is and gain massive performance improvements, mypyc it's a must!

Code sample:

    import time

    def fib(n: int) -> int:
        if n <= 1:
            return n
        else:
            return fib(n-2) + fib(n-1)


    startTime = time.time()
    fib(35)
    duration = time.time() - startTime
    msduration = duration * 1000.0
    uduration = msduration * 1000.0
    print(f'{duration:.6f} seconds, {msduration:.2f} ms, {uduration:.2f} μs')


    $ python3 mypyfib.py 
    1.452477 seconds, 1452.48 ms, 1452477.22 μs

    $ # the same code compiled with `mypyc mypyfib.py` produces the following:
    $ python3 -c "import mypyfib"
    0.063701 seconds, 63.70 ms, 63700.91 μs

This is huge, if you think about it!

       95.61% reduction in time
     2180.15% increase in performance
       22.80x faster

[1] https://github.com/mypyc/mypyc
[–] jech 1 day ago
This benchmark only measures function call overhead, which is important but not the whole story. What kind of figures do you get with a more realistic benchmark?
[–] stefanos82 12 hours ago
No idea why my original reply is not visible, nor marked as [dead]...such a weird behavior by HN!

Here's what I have replied to you:

To be honest with you, I am not sure how to answer your question.

What I can say is that when you identify bottlenecks within a project -- whether using Cython or mypyc -- the goal is to improve code performance by optimizing the specific parts that impact the project as a whole.

Naturally, the objective is not to replace the entire codebase (switching from Python to Cython), but rather to use the right tool for the job.

In this instance, that tool is mypyc; it requires no changes to your existing code -- it simply generates a Python module that you can then import into your project.

I hope my answer satisfies you, even just by a bit.