Skip to main content
 首页 » 编程设计

python之大型 if 语句减慢了我的脚本

2025年05月04日9mfrbuaa

我使用带有多个条件的 if 语句来根据用户输入过滤脚本的输出。

它有效,但唯一的问题是它大大地减慢了我的脚本

作为引用,该脚本是一个类似于 pcap 的数据包嗅探器,但使用套接字编写。

它打印输出的速度非常快,我猜是有一个大的 if 语句导致它变慢了。

if sourceaddress in (s_addr,"any") and sourceport in (source_port,"any") and filterprotocol in (6,"any"): 

这就是我目前使用的。问题是我必须至少添加 5 条语句才能完成我的脚本。我能做些什么来解决这个问题 *如果有的话

请您参考如下方法:

如果这是您代码的瓶颈,您必须拥有真正好的代码(我建议使用像 cProfile 这样的分析器来查找其他瓶颈。但是如果您想要优化它,它简单地做可能会更快一些:

if (sourceaddress == s_addr or sourceaddress == "any") and (sourceport==source_port or sourceport == "any") and (filterprotocol == 6 or filterprotocol == "any"):