【问题标题】:Parsing a UInt8 Array of chars into a float without allocation将 UInt8 字符数组解析为浮点数而无需分配
【发布时间】:2021-10-04 07:25:52
【问题描述】:

我这里有个问题:

function main()
    b = UInt8[0x35, 0x30, 0x2e, 0x30] # This is "50.0" in bytes
    s = parse(Float64, String(b))
end
@btime main()

250.269 ns (2 allocations: 128 bytes)
50.0

我有一个 UInt8 数组,其中包含一个字符串格式的数字,例如“50.0”。我想尽可能快地将这个数字解析成一个没有分配的浮点数(我有数百万个这样的数字要解析)。有没有比我上面生成的方法更好的方法(忽略 UInt8 数组的分配,因为这将不存在)。

干杯!

【问题讨论】:

    标签: performance julia heap-memory allocation


    【解决方案1】:

    你可以使用:

    julia> using Parsers
    
    julia> b = UInt8[0x35, 0x30, 0x2e, 0x30] # This is "50.0" in bytes
    4-element Vector{UInt8}:
     0x35
     0x30
     0x2e
     0x30
    
    julia> @btime Parsers.parse(Float64, $b)
      13.527 ns (0 allocations: 0 bytes)
    50.0
    

    请注意,您的代码在main 内分配b,因此它包括创建b 的时间和内存分配。

    另外不同的是,在您的代码中 String(b) 清空 b,而在 Parsers.parse 中,b 保持不变。如果bUInt8 值的较长磁带片段的视图,这将特别有用。

    【讨论】:

    • 感谢您的回答,特别是您的解释,这行得通。
    猜你喜欢
    • 1970-01-01
    • 2021-06-30
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多