Back to index

lightning-sunbird  0.9+nobinonly
pyxpcom_test_tools.py
Go to the documentation of this file.
00001 # test tools for the pyxpcom
00002 
00003 # export a "getmemusage()" function that returns a useful "bytes used" count
00004 # for the current process.  Growth in this when doing the same thing over and
00005 # over implies a leak.
00006 
00007 try:
00008     import win32api
00009     import win32pdh
00010     import win32pdhutil
00011     have_pdh = 1
00012 except ImportError:
00013     have_pdh = 0
00014 
00015 # XXX - win32pdh is slow, particularly finding our current process.
00016 # A better way would be good.
00017 
00018 # Our win32pdh specific functions - they can be at the top-level on all 
00019 # platforms, but will only actually be called if the modules are available.
00020 def FindMyCounter():
00021     pid_me = win32api.GetCurrentProcessId()
00022 
00023     object = "Process"
00024     items, instances = win32pdh.EnumObjectItems(None,None,object, -1)
00025     for instance in instances:
00026         # We use 2 counters - "ID Process" and "Working Set"
00027         counter = "ID Process"
00028         format = win32pdh.PDH_FMT_LONG
00029 
00030         hq = win32pdh.OpenQuery()
00031         path = win32pdh.MakeCounterPath( (None,object,instance, None, -1,"ID Process") )
00032         hc1 = win32pdh.AddCounter(hq, path)
00033         path = win32pdh.MakeCounterPath( (None,object,instance, None, -1,"Working Set") )
00034         hc2 = win32pdh.AddCounter(hq, path)
00035         win32pdh.CollectQueryData(hq)
00036         type, pid = win32pdh.GetFormattedCounterValue(hc1, format)
00037         if pid==pid_me:
00038             win32pdh.RemoveCounter(hc1) # not needed any more
00039             return hq, hc2
00040         # Not mine - close the query and try again
00041         win32pdh.RemoveCounter(hc1)
00042         win32pdh.RemoveCounter(hc2)
00043         win32pdh.CloseQuery(hq)
00044     else:
00045         raise RuntimeError, "Can't find myself!?"
00046 
00047 def CloseCounter(hq, hc):
00048     win32pdh.RemoveCounter(hc)
00049     win32pdh.CloseQuery(hq)
00050 
00051 def GetCounterValue(hq, hc):
00052     win32pdh.CollectQueryData(hq)
00053     format = win32pdh.PDH_FMT_LONG
00054     type, val = win32pdh.GetFormattedCounterValue(hc, format)
00055     return val
00056 
00057 g_pdh_data = None
00058 # The pdh function that does the work
00059 def pdh_getmemusage():
00060     global g_pdh_data
00061     if g_pdh_data is None:
00062         hq, hc = FindMyCounter()
00063         g_pdh_data = hq, hc
00064     hq, hc = g_pdh_data
00065     return GetCounterValue(hq, hc)
00066 
00067 # The public bit
00068 if have_pdh:
00069     getmemusage = pdh_getmemusage
00070 else:
00071     def getmemusage():
00072         return 0