performance - 使用计数器是一种好习惯吗?

标签 performance algorithm for-loop counter julia

这里有两个替代代码(用 Julia 编码),它们基本上做同样的事情。

counter = 0
for i = myArray
    counter = counter + 1
    Do1(i)
    Do2(counter)
end

for counter = 1:length(myArray)
    i = myArray[counter]
    Do1(i)
    Do2(j)
end

什么是好的做法?哪个代码更快?哪个代码消耗的内存更少?哪个代码更不容易出错?为什么?

最佳答案

在 julia 中,你可以很容易地测试它:

function indexing(A)
    si = 0
    sA = zero(eltype(A))
    for i = 1:length(A)
        sA += A[i]
        si += i
    end
    si, sA
end

function counter(A)
    si = 0
    sA = zero(eltype(A))
    i = 0
    for a in A
        sA += a
        si += (i += 1)
    end
    si, sA
end

function enumrt(A)
    si = 0
    sA = zero(eltype(A))
    for (i, a) in enumerate(A)
        sA += a
        si += i
    end
    si, sA
end

A = rand(Float32, 10^8)
# Compile all the functions, including those needed to time things
indexing(A)
counter(A)
enumrt(A)
@time 1+1

# Test the timing
@time indexing(A)
@time counter(A)
@time enumrt(A)

输出:

elapsed time: 4.61e-6 seconds (80 bytes allocated)
elapsed time: 0.12948093 seconds (144 bytes allocated)
elapsed time: 0.191082557 seconds (144 bytes allocated)
elapsed time: 0.331076493 seconds (160 bytes allocated)

如果你在每个循环之前添加 @inbounds 注释,那么你会得到这个:

elapsed time: 4.632e-6 seconds (80 bytes allocated)
elapsed time: 0.12512546 seconds (144 bytes allocated)
elapsed time: 0.12340103 seconds (144 bytes allocated)
elapsed time: 0.323285599 seconds (160 bytes allocated)

所以前两者之间的区别实际上只是自动删除边界检查的有效性。最后,如果你真的想深入细节,你可以使用 @code_native indexing(A) 检查生成的机器码,或者使用 @code_llvm 检查 LLVM IR (内部表示)。

但是,在某些情况下可读性可能更重要,因此 enumerate 方法是我经常使用的方法(但不是在真正的性能关键代码中)。

关于performance - 使用计数器是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27577162/

相关文章:

algorithm - OpenCV 计算图像平方 Assertion failed 错误

algorithm - 给定 N 个事件中每一个事件的概率,如何确定 0 到 N 个事件发生的概率?

ios - 在 for 循环中类型转换数组元素

javascript - 如何使用 for() 实现 .map()?

performance - 分析调用其他函数的函数的性能

c++ - 在 std::array 上使用 std::get 会提供更好的性能吗?

performance - WaIISHost 扁平化 Web 角色

c# - 为什么 LINQ (c#) 与 Seq (f#) 之间存在性能差异

java - 使用数组 io java 结果错误

c - 开始程序有问题