<p>我对Cython没有太多经验,所以这只是一个例子,说明Cython也可以进行计时</p>
<p><strong>示例</strong></p>
<pre><code>import numpy as np
import numba as nb
@nb.njit(cache=True)
def return_call(data_in):
#If the input is not contigous the reshape will fail
#-> make a c-contigous copy if the array isn't c-contigous
data=np.ascontiguousarray(data_in)
num = int(data.shape[0] / 4096)
buff_spectrum = np.zeros(2048,dtype= np.uint64)
buff_detect = np.zeros(2048,dtype= np.uint64)
end_spetrum = np.zeros(num*1024,dtype=np.float64)
end_detect = np.zeros(num*1024,dtype= np.float64)
_data = np.reshape(data,(num,4096))
#for _raw_data_spec in _data: is not supported
#but the followin works
for x in range(_data.shape[0]):
raw_data_spec = np.reshape(_data[x],(2048,2))
for i in range(2048):
buff_spectrum[i] = (np.int16(raw_data_spec[i][0])<<17)|(np.int16(raw_data_spec[i][1] <<1))>>1
buff_detect[i] = (np.int16(raw_data_spec[i][0])>>15)
for i in range (511,-1,-1):
if buff_spectrum[i+1024] != 0:
end_spetrum[i]=(np.log10(buff_spectrum[i+1024]))
end_detect[i]=buff_detect[i+1024]
else:
end_spetrum[i] =0
end_detect[i] = 0
for i in range(1023, 511, -1):
if buff_spectrum[i+1024] != 0:
end_spetrum[i] = (np.log10(buff_spectrum[i + 1024]))
end_detect[i] = buff_detect[i + 1024]
else:
end_spetrum[i] = 0
end_detect[i] = 0
return end_spetrum, end_detect
</code></pre>
<p><strong>计时</strong></p>
<pre><code>data = np.random.rand(8192*2)*20
data=data.astype(np.int16)
#with compilation
%timeit end_spetrum, end_detect=return_call(data)
#32.7 µs ± 5.61 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)
#without compilation
%timeit end_spetrum, end_detect=return_call_orig(data)
#106 ms ± 448 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>