Last active
February 3, 2022 13:53
-
-
Save hisui/10004131 to your computer and use it in GitHub Desktop.
[iOS] Getting current CPU usage.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <mach/mach.h> | |
// http://stackoverflow.com/questions/8223348/ios-get-cpu-usage-from-application | |
double getCurrentCPUUsage() | |
{ | |
thread_array_t threads; | |
mach_msg_type_number_t threadCount; | |
if (task_threads(mach_task_self(), &threads, &threadCount) != KERN_SUCCESS) { | |
return -1; | |
} | |
double usage = 0; | |
for (int i = 0; i < threadCount; i++) { | |
thread_info_data_t threadInfo; | |
mach_msg_type_number_t threadInfoCount = THREAD_INFO_MAX; | |
if (thread_info(threads[i], THREAD_BASIC_INFO, (thread_info_t) threadInfo, &threadInfoCount) != KERN_SUCCESS) { | |
usage = -1; | |
break; | |
} | |
auto info = (thread_basic_info_t) threadInfo; | |
if ((info->flags & TH_FLAGS_IDLE) == 0) { | |
usage += double(info->cpu_usage) / TH_USAGE_SCALE; | |
} | |
} | |
vm_deallocate(mach_task_self(), (vm_offset_t) threads, threadCount * sizeof(thread_t)); | |
return usage; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
UIImage *takeSnapshot() | |
{ | |
UIWindow *window = UIApplication.sharedApplication.windows[0]; | |
if ([UIScreen.mainScreen respondsToSelector:@selector(scale)]) { | |
UIGraphicsBeginImageContextWithOptions(window.bounds.size, NO, UIScreen.mainScreen.scale); | |
} | |
else { | |
UIGraphicsBeginImageContext(window.bounds.size); | |
} | |
[window.layer renderInContext:UIGraphicsGetCurrentContext()]; | |
auto image = UIGraphicsGetImageFromCurrentImageContext(); | |
UIGraphicsEndImageContext(); | |
return image; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment