【问题标题】:How to Efficiently convert C/C++ logic into python?如何有效地将 C/C++ 逻辑转换为 python?
【发布时间】:2018-01-12 00:26:50
【问题描述】:

我有一个 .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 中是否有任何有效的方法来做同样的事情?

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

【问题讨论】:

  • 这不是您在任何一种语言中索引的方式。贴出真实代码。
  • 我很惊讶 Python 只慢了四倍。如果您期望 Python 与 C++ 一样快,那么您正在打一场失败的战斗。您唯一的选择是其他 Python 解释器或为 Python 使用 C++ 模块。
  • @tadman,我不希望比 c++ 更快,但我只是不希望处理时间有那么大的差异。
  • 否则你可以使用range()函数的步幅:range(0, num_of_row_of_matrix_1 - 1, 2)而不是乘以2。
  • 没有 C/C++ 语言。 .cpp 源文件强烈建议使用 C++,但显示的代码在这两种语言中都没有意义(逗号不会像您在这里所期望的那样)。请选择一种语言并删除另一种标记,然后修复代码,谢谢。

标签: python c++ c python-2.7


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:
    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],这并不需要时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-14
      相关资源
      最近更新 更多