python 中计算信号功率的有效方法

Efficient way for calculating power of signal in python

我有 n_sample 个大脑信号,我想计算每个样本的功率。

这是我的代码:

def return_power_of_signal(input_signal):
    #The power of a signal is the sum of the absolute squares of its time-domain samples divided 
    #by the signal length, or, equivalently, the square of its RMS level.
    #my approach
    
    #input: np.array of (n_sample, time_length)
    
    n_sample = input_signal.shape[0]
    n_time = input_signal.shape[1]
    
    results_array = np.empty((n_sample, 1))
    
    for i in range(n_sample):
        sum_sample = 0
        for j in range(n_time):
            sum_sample += input_signal[i, j]*input_signal[i, j]
        sum_sample = sum_sample/n_time
        results_array[i] = sum_sample
    
    return results_array

但是,我想知道有没有更好的方法(更多 efficient/less 编码?)计算这个的方法?

谢谢

用np.abs(input_signal)**2,这个取绝对值,然后平方运算得到幅值