Luv
Luv

Reputation: 592

What is a quick way to get a linear combination of two large arrays?

I have two numpy arrays A and B of dimension (87256 X 87256).

I have a single factor alpha which I keep changing.

I am trying to find the fastest way of getting:

alpha * A + (1 - alpha) * B

Using simple numpy, it takes around 4 min 8 s to calculate.

What is the quickest way of calculating this array? I have a multi-core system, so parallel computing is not a limitation.

Upvotes: 2

Views: 707

Answers (2)

CypherX
CypherX

Reputation: 7353

Try these two options:

Option-A

# multiplying only once
C = B + alpha*(A-B)

Option-B

I expanded on @Massifox's answer.

import numba
import numpy as np

def get_result(A, B, alpha = 0.5):
    return B + alpha*(A-B)

get_result_jit = numba.vectorize(['float64(float64, float64, float64)'])(get_result)

Other resources:

  1. Numba tutorial
  2. See decorators for: @numba.vectorize, @numba.guvectorize and @numba.jit and @numba.njit.
  3. Speeding up algorithms with Numba

Upvotes: 1

Massifox
Massifox

Reputation: 4487

Try to switch to Numba changing very few lines of code put the turbo on your Numpy: parallelizing your code by taking full advantage of the CPU multicores and / or GPU cores.

Numba is an open source JIT compiler that translates a subset of Python and NumPy code into fast machine code.

Upvotes: 1

Related Questions