[英]Fastest way to convert a binary list(or array) into an integer in Python
[英]Fastest Way to convert a Binary String to Binary Array (Array of 1 and 0)
我试图找到将二进制字符串转换为整数0
和1
的数组的最快方法。 我目前正在使用python 3.8,并且有以下两个函数来获取这样的数组:
import numpy as np
from typing import Literal, Sequence
def string_to_array(Bin_String):
Bin_array=[int(Bin_String[i],2) for i in range(len(Bin_String))]
return Bin_array
def string_to_array_LtSq(string: Sequence[Literal['0', '1']]) -> np.ndarray:
return np.array([int(c) for c in string])
对于长度为 1024 的字符串, string_to_array_LtSq
函数比另一个函数花费的时间少 20 微秒(平均 370 微秒),但我不明白为什么它更快,因为两者都使用int
函数。
但这是代码的重要部分,那么python中有没有更快的方法?
此外,是否可以用任何其他语言(例如 c)做得更快? 我可能会切换到那种语言。
谢谢。
相关帖子:
尝试:
s = '0011'
print(np.frombuffer(s.encode("ascii"), dtype="u1") - 48)
基准:
import numpy as np
from timeit import timeit
s = "1011" * 256 # length = 1024
def f1():
return np.frombuffer(s.encode("ascii"), dtype="u1") - 48
def f2():
return np.array([int(c) for c in s])
def f3():
return list(map(int, s))
def f4():
return [int(c) for c in s]
t1 = timeit(f1, number=1_000)
t2 = timeit(f2, number=1_000)
t3 = timeit(f3, number=1_000)
t4 = timeit(f4, number=1_000)
print(t1)
print(t2)
print(t3)
print(t4)
印刷:
0.00223864201689139
0.18963027599966154
0.10751374304527417
0.13433810899732634
编辑:添加了仅创建 python 列表的函数(而不是 np.array)
bytearray
似乎比 Andrej 的 NumPy 解决方案更快。 bytes
可用于快速list
解决方案。 1024 位的时间(仅显示前 5 位):
f1 2.7 μs [1 0 1 1 1]
f2 2.0 μs bytearray(b'\x01\x00\x01\x01\x01')
f3 7.6 μs [1, 0, 1, 1, 1]
基于 Andrej 的代码( 在线试用! ):
import numpy as np
from timeit import timeit
s = "1011" * 256 # length = 1024
def f1():
return np.frombuffer(s.encode("ascii"), dtype="u1") - 48
table = bytearray.maketrans(b'01', b'\x00\x01')
def f2():
return bytearray(s, "ascii").translate(table)
def f3():
return [*s.encode().translate(table)]
for _ in range(3):
for f in f1, f2, f3:
t = timeit(f, number=1_000)
t = '%5.1f μs ' % (t * 1e3)
print(f.__name__, t, f()[:5])
print()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.