2

I'm using an if statement with multiple conditions to filter the output of my script based on user-input.

It works, but the only problem is that it slows down my script greatly

For a refrence, the script is a packet sniffer like pcap but written with sockets.

It prints the output very quickly and im guessing having a large if statement is what is slowing it down.

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

That's what i am currently using. And the thing is there is at least 5 more statements i have to add in there to complete my script. What could i do to fix this *If anything

John Don
  • 45
  • 3
  • You could put the least likely condition first and short circuit any unnecessary processing. – erip Feb 16 '15 at 05:46
  • it's not the `if`. It is most likely the series of look up in the if conditions. – taesu Feb 16 '15 at 05:46
  • 2
    How do you know that `if`-statement slowing down your script? Have you measured it (e.g., to measure CPU-bound code, run `python3 -mprofile your_script.py`)? Unless a profiler says so; it is unlikely that it is a bottleneck in your application. – jfs Feb 16 '15 at 05:50
  • `If` those look-ups inside your condition statements are really the source of your performance loss, you could try to find ways to short circuit as erip suggested, `elif` you already have some other less elegant code that may do the job more efficiently `or` if you can somehow reduce the overhead elsewhere in your code, I'd suggest you try _that_, `else` you may just have to live with it. – Eithos Feb 16 '15 at 05:50

2 Answers2

1

You must have really good code if this is the bottleneck of your code (I recommend using a profiler like cProfile to find other bottlenecks. But if you're looking to optimize it, it will probably be a little faster to simply do:

if (sourceaddress == s_addr or sourceaddress == "any") and (sourceport==source_port or sourceport == "any") and (filterprotocol == 6 or filterprotocol == "any"):
Community
  • 1
  • 1
nico
  • 2,022
  • 4
  • 23
  • 37
  • Ill try that out now, i have tried many different things so i'm certain its the if statement. removing it, changing it, shortening it. all had different affects. – John Don Feb 16 '15 at 05:50
  • I timed it and it is approximately 14% faster to do it this way. Still, I would suspect your bottleneck is elsewhere. – nico Feb 16 '15 at 06:03
0

Python works faster on immutable variables, so change your variables to immutable if you can. Or make them immutable in if statement, like a tuple. Convert them to a tuple if it's not going to broke any thing.

GLHF
  • 3,835
  • 10
  • 38
  • 83