I have several different functions that all loop recursively through all the active processes on my system using the wmi module. If it would help, here is basically how it loops through without any optimization:
c = wmi.WMI ()
for process in c.Win32_Process ():
#do various thing here, like find if there is a process running with a certain name, et cetera
For some reason, this takes a surprisingly long time. I have used psutils to do the same thing. For several reasons, I am not using psutils. After looking through the python wiki page on optimization at https://wiki.python.org/moin/PythonSpeed/PerformanceTips, it looks like there are three things I could do to speed this up. One of them is to use generator expressions, which should work. However, it also talks about using local variables, as well as avoiding "dots." If I call some of the same classes and methods from different methods, I could reduce dots by naming something like c.Win32_Process a variable to access from these functions. However, this would also create a global variable, which is slower than a local variable. Which is better? Here is a basic picture of the two approaches (without the generator expression):
Way 1:
def list_processes():
c = wmi.WMI ()
for process in c.Win32_Process ():
print process.ProcessId, process.Name
def grep_process(name):
c = wmi.WMI ()
for process in c.Win32_Process ():
if name in process.Name:
return process.ProcessId
return None
Way 2
task_manager = wmi.WMI ()
def list_processes():
for process in task_manager.Win32_Process ():
print process.ProcessId, process.Name
def grep_process(name):
for process in task_manager.Win32_Process ():
if name in process.Name:
return process.ProcessId
return None
Also, is this a viable third solution to get the best of both worlds?
def manage_processes(command):
task_manager = wmi.WMI ()
if command == "list_processes":
for process in task_manager.Win32_Process ():
print process.ProcessId, process.Name
elif command == "grep_process"
for process in task_manager.Win32_Process ():
if name in process.Name:
return process.ProcessId
return None
These changes probably won't change the speed a lot, but it is slow enough that I would like to try to optimize it at least somewhat. If there are any other ways to speed this up, I would be grateful to hear about those, too.