【问题标题】:Reducing memory allocations when building Vector{UInt8} from parts从部件构建 Vector{UInt8} 时减少内存分配
【发布时间】:2021-10-23 19:01:08
【问题描述】:

我希望从不同的部分构建一个 Vector{UInt8},如下所示:

using BenchmarkTools
using Random

const a = Vector{UInt8}("Number 1: ")
const b = Vector{UInt8}(", Number 2: ")
const c = Vector{UInt8}(", Number 3: ")
const d = Vector{UInt8}(", Number 4: ")

function main(num2, num4)::Vector{UInt8}

    return vcat(
        a,
        Vector{UInt8}(string(rand(1:100))),
        b,
        Vector{UInt8}(string(num2)),
        c,
        Vector{UInt8}(string(rand(1:100))),
        d,
        Vector{UInt8}(string(num4)),
    )

end

@btime main(70.45, 12) # 486.224 ns (13 allocations: 1.22 KiB)
#Example output: "Number 1: 50, Number 2: 70.45, Number 3: 10, Number 4: 12"

转换为字符串然后 Vector{UInt8} 似乎是错误的。我不介意加入向量时发生的 1 分配。

【问题讨论】:

  • 您能解释一下为什么将数字转换为字符串吗?你想做什么?
  • 如果你想创建一个随机字符串,你不能写string("Number 1: ", rand(1:100), ", Number 2: 70.45") 吗?
  • 我想用 Vector{UInt8} 表示而不是字符串。我可以创建一个字符串,然后在其上使用 Vector{UInt8} ,但它分配给字符串和数组
  • 那么Vector{UInt8} 版本的随机数字符串表示?你已经硬编码了数字70.45,这是否意味着你可以用预先计算的值替换它,或者这个数字可以改变吗?在这里使用整数和浮点数是完全不同的。
  • 这个数字可以改变,由用户在函数中提供。我将同时使用整数和浮点数

标签: string julia byte allocation low-latency


【解决方案1】:

将整数转换为UInt8 格式的数字向量可以非常有效地完成。转换浮点数有点棘手。

总而言之,我认为您的代码已经非常高效了。这是加速整数代码的建议。浮点代码,我一直没能改进:

function tobytes(x::Integer)
    N = ndigits(x)
    out = Vector{UInt8}(undef, N)
    for i in N:-1:1
        (x, r) = divrem(x, 0x0a)
        out[i] = UInt8(r) + 0x30
    end
    return out
end

tobytes(x) = Vector{UInt8}(string(x))

# notice that we generate random UInt8 values instead of rand(1:100), as this is faster. They still have to be converted according to the character interpretation, though.
function main2(num2, num4)
    [a; tobytes(rand(0x01:0x64)); b; tobytes(num2); c; tobytes(rand(0x01:0x64)); d; tobytes(num4)]
end

tobytes 用于整数现在接近最优,运行时主要是预分配 Vector{UInt8} 的时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 2019-08-21
    相关资源
    最近更新 更多