【问题标题】:Cython fast list / numpy accessingCython 快速列表/numpy 访问
【发布时间】:2021-12-06 09:35:26
【问题描述】:

我有一个我正在尝试加速的 Python 函数,它只需要一行 tshark 输出,例如:

'1\t0.000000000\tTCP\t100.0.1.190,111.0.0.2\t35291\t55321\t\t\t56\t20\t··········S·\t36\n'

并将数据分配给如下变量:

            arr = line.strip('\n').split("\t")

            sip = arr[3].split(',')[0]
            dip = arr[3].split(',')[1]

            s_flag = 1 if 'S' in arr[10] else '0'
            a_flag = 1 if 'A' in arr[10] else '0'
            f_flag = 1 if 'F' in arr[10] else '0'
            r_flag = 1 if 'R' in arr[10] else '0'
            p_flag = 1 if 'P' in arr[10] else '0'
            u_flag = 1 if 'U' in arr[10] else '0'
            e_flag = 1 if 'E' in arr[10] else '0'
            c_flag = 1 if 'C' in arr[10] else '0'

有什么方法可以使用 Cython 加快速度?我正在考虑将 line.strip('\n').split("\t") 的结果转换为 numpy 数组,因为我听说它比 Cython 中的 Python 列表更快?我还能如何加快速度? 例如:

import numpy
cimport numpy

arr = np.array(line.strip('\n').split("\t"))

这行得通吗?提前谢谢!

【问题讨论】:

  • flags = {}, for char in char_flags: flags[char + "_flag"] = 1 if char.upper() in arr[10] else '0' 其中 charflags 是 "s", "a", ...。请注意,这会将结果存储在 dict 中。
  • 您确定这不够快吗? ··········S· 是否总是以相同的顺序,每个缺失的字符都替换为.
  • c_flag = 1 if 'C' in arr[10] else '0' 似乎很奇怪。 1 (int) 或 '0' (str)。也许改用布尔值:c_flag = ('C' in arr[10])。使用 numpy:np.isin(list('SAFRPUEC'), list(arr[10]))
  • @MadPhysicist 是的,我的代码花了大约 4 分钟来处理一分钟内发送的 930000 个数据包。当然,这个数据包数量可以是任意数量,具体取决于硬件,但我想尽量减少处理时间。是的,标志的顺序始终相同。
  • 那么使用 numpy 而不是 Python 列表有什么意义吗?还会有什么好处吗?如果你熟悉的话,你如何使用 numpy 对 Python 列表进行 cythonize 处理,如果它是这样工作的?我只是听说过这个概念。

标签: python numpy cython cythonize


【解决方案1】:

由于您正在处理字符串列表,numpy 甚至 cython 都可能对您没有多大帮助。您正在寻找的转换是如此微不足道,您只需稍微清理一下您的 python 代码并继续前进:

FLAGS = np.array(list('SAFRPUEC'))

items = line.strip('\n').split("\t")
sip, dip = items[3].split(',')
flags = dict(zip(FLAGS, np.isin(FLAGS, list(items[10]))))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多