Python equivalence to inline functions or macros

前端 未结 6 2262
天涯浪人
天涯浪人 2020-12-04 15:44

I just realized that doing

x.real*x.real+x.imag*x.imag

is three times faster than doing

abs(x)**2

where x

6条回答
  •  Happy的楠姐
    2020-12-04 15:56

    Not exactly what the OP has asked for, but close:

    Inliner inlines Python function calls. Proof of concept for this blog post

    from inliner import inline
    
    @inline
    def add_stuff(x, y):
        return x + y
    
    def add_lots_of_numbers():
        results = []
        for i in xrange(10):
             results.append(add_stuff(i, i+1))
    

    In the above code the add_lots_of_numbers function is converted into this:

    def add_lots_of_numbers():
        results = []
        for i in xrange(10):
             results.append(i + i + 1)
    

    Also anyone interested in this question and the complications involved in implementing such optimizer in CPython, might also want to have a look at:

    • Issue 10399: AST Optimization: inlining of function calls
    • PEP 511 -- API for code transformers (Rejected)

提交回复
热议问题