在OS X(10.6和10.7)上,是否有一种标准的方法可以使用Cocoa/Objective-C获取GPU使用百分比?
享受它吧,GPU 和 RAM 使用情况。顺便说一下,它不能在独立的 GPU 上运行,因为它没有公开性能监控字典。我的 MBP 有一个 NVIDIA GPU,ATI 也应该可以用,但我不确定百分之百。
#include <CoreFoundation/CoreFoundation.h>
#include <Cocoa/Cocoa.h>
#include <IOKit/IOKitLib.h>
int main(int argc, const char * argv[])
{
while (1) {
// Get dictionary of all the PCI Devicces
CFMutableDictionaryRef matchDict = IOServiceMatching(kIOAcceleratorClassName);
// Create an iterator
io_iterator_t iterator;
if (IOServiceGetMatchingServices(kIOMasterPortDefault,matchDict,
&iterator) == kIOReturnSuccess)
{
// Iterator for devices found
io_registry_entry_t regEntry;
while ((regEntry = IOIteratorNext(iterator))) {
// Put this services object into a dictionary object.
CFMutableDictionaryRef serviceDictionary;
if (IORegistryEntryCreateCFProperties(regEntry,
&serviceDictionary,
kCFAllocatorDefault,
kNilOptions) != kIOReturnSuccess)
{
// Service dictionary creation failed.
IOObjectRelease(regEntry);
continue;
}
CFMutableDictionaryRef perf_properties = (CFMutableDictionaryRef) CFDictionaryGetValue( serviceDictionary, CFSTR("PerformanceStatistics") );
if (perf_properties) {
static ssize_t gpuCoreUse=0;
static ssize_t freeVramCount=0;
static ssize_t usedVramCount=0;
const void* gpuCoreUtilization = CFDictionaryGetValue(perf_properties, CFSTR("GPU Core Utilization"));
const void* freeVram = CFDictionaryGetValue(perf_properties, CFSTR("vramFreeBytes"));
const void* usedVram = CFDictionaryGetValue(perf_properties, CFSTR("vramUsedBytes"));
if (gpuCoreUtilization && freeVram && usedVram)
{
CFNumberGetValue( (CFNumberRef) gpuCoreUtilization, kCFNumberSInt64Type, &gpuCoreUse);
CFNumberGetValue( (CFNumberRef) freeVram, kCFNumberSInt64Type, &freeVramCount);
CFNumberGetValue( (CFNumberRef) usedVram, kCFNumberSInt64Type, &usedVramCount);
NSLog(@"GPU: %.3f%% VRAM: %.3f%%",gpuCoreUse/(double)10000000,usedVramCount/(double)(freeVramCount+usedVramCount)*100.0);
}
}
CFRelease(serviceDictionary);
IOObjectRelease(regEntry);
}
IOObjectRelease(iterator);
}
sleep(1);
}
return 0;
}
vramUsedBytes
和GPU Core Utilization
已经不存在。解决方法是从IOAccelerator
或者IOPCIDevice
选取"VRAM,totalMB"
。例如,Intel GPU的VRAM在IOAccelerator
中,而AMD的VRAM在IOPCIDevice
中。在IOAccelerator
的PerformanceStatistics
中,你只能找到正在使用的GPU的vramFreeBytes
。GPU Core Utilization
已被重命名为Device Utilization %
或GPU Activity(%)
。 - Marc J. Schmidt