如何有效地将C / C++逻辑转换为python?

How to Efficiently convert C/C++ logic into python?

本文关键字:转换 python C++ 有效地      更新时间:2023-10-16

我有一个.cpp代码,如下所示,其中我正在将一些matrix_1值复制到matrix_2。

(注:最初matrix_2是matrix_1的副本。

num_of_row_of_matrix_1 = 400
num_of_col_of_matrix_1 = 700
for (int Row = 0; Row < num_of_row_of_matrix_1; Row += 2)
{
for (int Col = 0; Col < num_of_col_of_matrix_1; Col += 2)
{
matrix_2[Row + 1][Col] = matrix_1[Row][Col + 1];
}
}

现在我在 python-2.7 中实现的相同代码如下所示,

for Row in range(len(matrix_1)/2):
Row *= 2
for Col in range(len(matrix_1[0])/2):
Col *= 2
matrix_2[Row + 1, Col] = matrix_1[Row, Col + 1]

python中的矩阵就像

array([[1, 2, 3, ...,  33,  37,  36],
[4, 5, 6, ...,  25,  16,  26],
[2, 4, 7, ...,  37,  32,  36],
..., 
[ 35, 106,  36, ..., 151,  37, 141],
[114, 179, 119, ..., 2, 165, 133],
[ 37, 111,  34, ..., 144,  39, 139]], dtype=uint8)

python 中的转换速度比 cpp 慢约 4 倍。

有没有有效的方法可以在python中做同样的事情?

如果您需要更多信息以进行澄清,请告诉我。

看起来这些是 NumPy 数组。如果是这样,你可以做

matrix_2[1::2, ::2] = matrix_1[::2, 1::2]

以避免 Python 级循环和包装器对象构造的开销。

for Row in range(len(matrix_1)/2):
Row *= 2
for Col in range(len(matrix_1[0])/2):
Col *= 2
matrix_2[Row + 1, Col] = matrix_1[Row, Col + 1]

实际上,上面的代码是我在一个函数中编写的,我一次又一次地调用。我问了这个问题来改进它。

在此代码中,反复调用此matrix_2[Row + 1, Col] = matrix_1[Row, Col + 1]非常耗时,这只不过是检查索引并复制到另一个矩阵。

x = np.arange (0, num_of_row_of_matrix_1*num_of_col_of_matrix_1).reshape(num_of_row_of_matrix_1, num_of_col_of_matrix_1) h1, w1 = np.where (np.logical_and ( ((x/num_of_col_of_matrix_1)%2 == 0), (x%2 == 1))) h2, w2 = np.where (np.logical_and ( ((x/num_of_col_of_matrix_1)%2 == 1), (x%2 == 0)))

这给了我必须复制的内容的索引。由于这些索引是固定的,我需要复制,所以我把它放在函数之外。然后,在函数中,我只是复制选定的索引,例如matrix_2[h2, w2] = matrix_1[h1, w1]不需要时间。