在没有分配的情况下将 UInt8 字符数组解析为浮点数
Parsing a UInt8 Array of chars into a float without allocation
我遇到了这个问题:
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 数组的分配,因为它不存在)。
伙计们干杯!
您可以使用:
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
保持不变。如果 b
是 UInt8
值的较长磁带的切片视图,这将特别有用。
我遇到了这个问题:
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 数组的分配,因为它不存在)。
伙计们干杯!
您可以使用:
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
保持不变。如果 b
是 UInt8
值的较长磁带的切片视图,这将特别有用。