Simple RGB LED controller for Mac OS X
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

GPUStats.m 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // GPUStats.m
  3. // CaseLights
  4. //
  5. // Created by Thomas Buck on 23.12.15.
  6. // Copyright © 2015 xythobuz. All rights reserved.
  7. //
  8. #import <IOKit/IOKitLib.h>
  9. #import "GPUStats.h"
  10. @implementation GPUStats
  11. + (NSInteger)getGPUUsage:(NSNumber **)usage freeVRAM:(NSNumber **)free usedVRAM:(NSNumber **)used {
  12. if ((usage == nil) || (free == nil) || (used == nil)) {
  13. NSLog(@"Invalid use of getGPUUsage!\n");
  14. return 1;
  15. }
  16. *usage = nil;
  17. *free = nil;
  18. *used = nil;
  19. CFMutableDictionaryRef pciDevices = IOServiceMatching(kIOAcceleratorClassName);
  20. io_iterator_t iterator;
  21. if (IOServiceGetMatchingServices(kIOMasterPortDefault, pciDevices, &iterator) == kIOReturnSuccess) {
  22. io_registry_entry_t registry;
  23. while ((registry = IOIteratorNext(iterator))) {
  24. CFMutableDictionaryRef services;
  25. if (IORegistryEntryCreateCFProperties(registry, &services, kCFAllocatorDefault, kNilOptions) == kIOReturnSuccess) {
  26. CFMutableDictionaryRef properties = (CFMutableDictionaryRef)CFDictionaryGetValue(services, CFSTR("PerformanceStatistics"));
  27. if (properties) {
  28. const void *gpuUsage = CFDictionaryGetValue(properties, CFSTR("GPU Core Utilization"));
  29. const void *freeVRAM = CFDictionaryGetValue(properties, CFSTR("vramFreeBytes"));
  30. const void *usedVRAM = CFDictionaryGetValue(properties, CFSTR("vramUsedBytes"));
  31. if (gpuUsage && freeVRAM && usedVRAM) {
  32. // Found the GPU. Store this reference for the next call
  33. static ssize_t gpuUsageNum = 0;
  34. static ssize_t freeVRAMNum = 0;
  35. static ssize_t usedVRAMNum = 0;
  36. CFNumberGetValue((CFNumberRef)gpuUsage, kCFNumberSInt64Type, &gpuUsageNum);
  37. CFNumberGetValue((CFNumberRef)freeVRAM, kCFNumberSInt64Type, &freeVRAMNum);
  38. CFNumberGetValue((CFNumberRef)usedVRAM, kCFNumberSInt64Type, &usedVRAMNum);
  39. *usage = [NSNumber numberWithDouble:gpuUsageNum / (double)10000000];
  40. *free = [NSNumber numberWithDouble:freeVRAMNum];
  41. *used = [NSNumber numberWithDouble:usedVRAMNum];
  42. //NSLog(@"GPU: %.3f%% VRAM: %.3f%%\n", gpuUsageNum / (double)10000000,
  43. //usedVRAMNum / (double)(freeVRAMNum + usedVRAMNum) * 100.0);
  44. }
  45. }
  46. CFRelease(services);
  47. }
  48. IOObjectRelease(registry);
  49. }
  50. IOObjectRelease(iterator);
  51. } else {
  52. NSLog(@"Couldn't list PCI devices!\n");
  53. }
  54. if ((*usage != nil) && (*free != nil) && (*used != nil)) {
  55. return 0;
  56. } else {
  57. NSLog(@"Error reading GPU data!\n");
  58. return 1;
  59. }
  60. }
  61. @end