How to optimize a nested for loop in Python

前端 未结 3 754
轻奢々
轻奢々 2021-02-08 10:34

So I am trying to write a python function to return a metric called the Mielke-Berry R value. The metric is calculated like so:

The current code I have written works, b

3条回答
  •  我在风中等你
    2021-02-08 11:19

    As a reference, the following code:

    #pythran export mb_r(float64[], float64[])
    import numpy as np
    
    def mb_r(forecasted_array, observed_array):
        return np.abs(forecasted_array[:,None] - observed_array).sum()
    

    Runs at the following speed on pure CPython:

    % python -m perf timeit -s 'import numpy as np; x = np.random.rand(400); y = np.random.rand(400); from mbr import mb_r' 'mb_r(x, y)' 
    .....................
    Mean +- std dev: 730 us +- 35 us
    

    And when compiled with Pythran I get

    % pythran -march=native -DUSE_BOOST_SIMD mbr.py
    % python -m perf timeit -s 'import numpy as np; x = np.random.rand(400); y = np.random.rand(400); from mbr import mb_r' 'mb_r(x, y)'
    .....................
    Mean +- std dev: 65.8 us +- 1.7 us
    

    So roughly a x10 speedup, on a single core with AVX extension.

提交回复
热议问题