Python 如何加速整数值的二进制转换
我编写了以下方法(在Python2.7中)来生成一组整数并将其转换为二进制表示。它采用两个自解释的参数:Python 如何加速整数值的二进制转换,python,python-2.7,Python,Python 2.7,我编写了以下方法(在Python2.7中)来生成一组整数并将其转换为二进制表示。它采用两个自解释的参数:total_num_nodes和dim。它返回numpy矩阵,如包含所有这些整数的二进制表示: def generate(total_num_nodes, dim): # Generate random nodes from the range (0, dim-1) nodes_matrix = [random.randint(0, 2 ** dim - 1) for _
total_num_nodes
和dim
。它返回numpy矩阵,如包含所有这些整数的二进制表示:
def generate(total_num_nodes, dim):
# Generate random nodes from the range (0, dim-1)
nodes_matrix = [random.randint(0, 2 ** dim - 1) for _ in range(total_num_nodes)]
# Removes duplicates
nodes_matrix = list(set(nodes_matrix))
# Transforms each node from decimal to string representation
nodes_matrix = [('{0:0' + str(dim) + 'b}').format(x) for x in nodes_matrix]
# Transforms each bit into an integer.
nodes_matrix = np.asarray([list(map(int, list(x))) for x in nodes_matrix], dtype=np.uint8)
return nodes_matrix
问题是,当我传递非常大的值时,比如说total_num_nodes=10000000
和dim=128
,生成时间非常长。我的一位朋友暗示我,下面这行实际上是一个瓶颈,它可能会占用大部分计算时间:
# Transforms each node from decimal to string representation
nodes_matrix = [('{0:0' + str(dim) + 'b}').format(x) for x in nodes_matrix]
我想不出其他更快的方法来回复这一行,以便在单处理器上运行时加快生成时间。非常感谢您的任何建议
谢谢在numpy做这一切会更快 以下内容生成
np.uint8
数据的dim
列的total_num_节点
行,然后通过提供适合np.unique
的数据视图来保留唯一行,然后转换回2D数组:
import numpy as np
def generate(total_num_nodes, dim):
a = np.random.choice(np.array([0,1],dtype=np.uint8),size=(total_num_nodes,dim))
dtype = a.dtype.descr * dim
temp = a.view(dtype)
uniq = np.unique(temp)
return uniq.view(a.dtype).reshape(-1,dim)
与其猜测,不如尝试对程序进行基准测试。\@user202729非常感谢。我从没想过。我还是个中级程序员。我很惊讶地图是一条占用大部分时间的直线!!!稍后我会写一个完整的答案。现在,一个提示(在TIO上验证):使用
ord
@user202729非常感谢。我迫不及待地想看看你的答案。真是太棒了!谢谢你,所以我的方法还是比较慢的(大约2.5倍),所以我不会发布。(@Lauren)(使用a!=“0”
似乎比ord(a)-48略快一些)