Julia ---- 一種高效掃描Array中數據的方式

很多時候需要逐個掃描Array中數據,並根據計算規則計算數據。

這裏以對比數據爲例給出兩種計算方式:

1  使用內置函數all 過濾array

test_1(x) = all(y->y==x[1],x)

2 這裏有一個 自定義 函數,它使用了內聯函數。效率明顯提高了。

@inline function test_2(x)
    length(x) < 2 && return true
    e1 = x[1]
    i = 2
    @inbounds for i=2:length(x)
        x[i] == e1 || return false
    end
    return true
end

代碼效率對比,明顯第2種方式比較好

using BenchmarkTools

v = fill(1,10_000_000);

test_1(v)

test_2(v)

@btime test_1($v);
# 14.616 ms (0 allocations: 0 bytes)

@btime test_2($v);
#11.080 ms (0 allocations: 0 bytes)

v[100] = 2

@btime test_1($v);
#85.944 ns (0 allocations: 0 bytes)

@btime test_2($v);
#63.761 ns (0 allocations: 0 bytes)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章