我正在尝试从Python的pywin32包中使用win32pdhutil查询Windows性能计数器,但是只要计数器名称带有斜杠,我都会遇到错误。
例如,此代码可以正常工作:
import win32pdhutil
query = win32pdhutil.GetPerformanceAttributes("Memory", "Available Bytes")
但是此代码失败:
import win32pdhutil
query = win32pdhutil.GetPerformanceAttributes("Memory", "Cache Faults/sec")
错误消息是:
Traceback (most recent call last):
File "<path>\Python\Python38-32\lib\site-packages\win32\lib\win32pdhutil.py", line 61, in GetPerformanceAttributes
type, val = win32pdh.GetFormattedCounterValue(hc, format)
pywintypes.error: (-1073738810, 'GetFormattedCounterValue', 'The data is not valid.')
我尝试了许多不同的计数器,并且仅在计数器名称中有斜杠时才遇到此问题。
我的原始代码使用具有相同问题的win32pdh.AddCounter和win32pdh.CollectQueryData,但是上面的示例在一行中进行了演示。
我找到了相似的线程here,没有明显的解决方案。
您需要等待“缓存故障/秒”来收集足够的数据,这是msdn上用于Performance Counters api的c ++示例:
并且在python中,如果我在win32pdhutil.py的GetPerformanceAttributes
函数中硬编码(仅用于测试),如下所示:
def GetPerformanceAttributes(object, counter, instance = None, inum=-1,
format = win32pdh.PDH_FMT_LONG, machine=None):
# NOTE: Many counters require 2 samples to give accurate results,
# including "% Processor Time" (as by definition, at any instant, a
# thread's CPU usage is either 0 or 100). To read counters like this,
# you should copy this function, but keep the counter open, and call
# CollectQueryData() each time you need to know.
# See http://support.microsoft.com/default.aspx?scid=kb;EN-US;q262938
# and http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
# My older explanation for this was that the "AddCounter" process forced
# the CPU to 100%, but the above makes more sense :)
path = win32pdh.MakeCounterPath( (machine,object,instance, None, inum,counter) )
hq = win32pdh.OpenQuery()
try:
hc = win32pdh.AddCounter(hq, path)
try:
win32pdh.CollectQueryData(hq)
time.sleep(1)
win32pdh.CollectQueryData(hq)
type, val = win32pdh.GetFormattedCounterValue(hc, format)
return val
finally:
win32pdh.RemoveCounter(hc)
finally:
win32pdh.CloseQuery(hq)
然后"Cache Faults/sec"
为我工作,您可以尝试自定义自己的m_GetFormattedCounterValue
函数,然后给收集器足够的时间来收集数据,如上面的示例。