iOS 實時獲取當前應用消耗的CPU和內(nèi)存

https://www.cnblogs.com/mobilefeng/p/4977783.html
這一遍文章對獲取app 消耗的CPU和內(nèi)存問題的多種方案做了對比狸臣,沒有實際去測試。

1 獲取應用消耗的CPU

float cpu_usage()
{
    kern_return_t kr;
    task_info_data_t tinfo;
    mach_msg_type_number_t task_info_count;

    task_info_count = TASK_INFO_MAX;
    kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
    if (kr != KERN_SUCCESS) {
        return -1;
    }

    task_basic_info_t      basic_info;
    thread_array_t         thread_list;
    mach_msg_type_number_t thread_count;

    thread_info_data_t     thinfo;
    mach_msg_type_number_t thread_info_count;

    thread_basic_info_t basic_info_th;
    uint32_t stat_thread = 0; // Mach threads

    basic_info = (task_basic_info_t)tinfo;

    // get threads in the task
    kr = task_threads(mach_task_self(), &thread_list, &thread_count);
    if (kr != KERN_SUCCESS) {
        return -1;
    }
    if (thread_count > 0)
        stat_thread += thread_count;

    long tot_sec = 0;
    long tot_usec = 0;
    float tot_cpu = 0;
    int j;

    for (j = 0; j < thread_count; j++)
    {
        thread_info_count = THREAD_INFO_MAX;
        kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
                         (thread_info_t)thinfo, &thread_info_count);
        if (kr != KERN_SUCCESS) {
            return -1;
        }

        basic_info_th = (thread_basic_info_t)thinfo;

        if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
            tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
            tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;
            tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
        }

    } // for each thread

    kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
    assert(kr == KERN_SUCCESS);

    return tot_cpu;
}

對于該方法獲取的CPU消耗情況與Xcode 實時監(jiān)控的CPU消耗情況基本一致蜒茄。

2. 獲取應用消耗的內(nèi)存

該方法計算出來的內(nèi)存消耗情況落剪,與Xcode 統(tǒng)計的消耗情況相差太大(參考性不太大)。

還是貼出來:

// 有的是除以1024场靴,有的是除以1000啡莉。
+ (float)memoryUsage
{
    vm_size_t memory = memory_usage();
    return memory / 1000.0 /1000.0;
}

vm_size_t memory_usage(void) {
    struct task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);
    return (kerr == KERN_SUCCESS) ? info.resident_size : 0; // size in bytes
}

然后寫一個單例類港准,添加一個定時器,隔一段時間調(diào)用一下該方法獲取當前的內(nèi)存和CPU消耗情況咧欣,同時寫入本地文件中浅缸,以便后期分析。

簡單寫了一下魄咕,實現(xiàn)如下:

#import "HLMonitor.h"
#import <mach/mach.h>
#import <sys/time.h>

static HLMonitor *instance = nil;

@interface HLMonitor ()

@property (nonatomic, assign) NSTimeInterval  timeInterval;

@end

@implementation HLMonitor

+ (instancetype)sharedInstance
{
    return [[[self class] alloc] init];
}

- (instancetype)init
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super init];
    });

    return instance;
}

+ (instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [super allocWithZone:zone];
    });
    return instance;
}

- (void)startMonitorWithTimeInterval:(NSTimeInterval)timeInterval
{
    if (timeInterval <= 0) {
        timeInterval = 1.0;
    }
    self.timeInterval = timeInterval;

    NSString *filePath = [HLMonitor cpu_memoryLogPath];
    NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:filePath];
    [fileHandler seekToEndOfFile];
    NSString *startLog = @"******************************開始統(tǒng)計cpu 和內(nèi)存************************\n";
    [fileHandler writeData:[startLog dataUsingEncoding:NSUTF8StringEncoding]];
    [self saveMonitorLog];
}

- (void)saveMonitorLog
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        float cpuUsage = [HLMonitor cpuUsage];
        float memoryUsage = [HLMonitor memoryUsage];

        struct tm* timeNow = [HLMonitor getCurTime];
        NSString *monitorLog = [NSString stringWithFormat:@"%d-%d-%d %d:%d:%d.%ld | cpu 使用率:%.2f ----內(nèi)存使用:%f\n",
                                timeNow->tm_year,
                                timeNow->tm_mon,
                                timeNow->tm_mday,
                                timeNow->tm_hour,
                                timeNow->tm_min,
                                timeNow->tm_sec,
                                timeNow->tm_gmtoff,
                                cpuUsage,
                                memoryUsage];
        NSLog(@"%@",monitorLog);
        NSString *filePath = [HLMonitor cpu_memoryLogPath];
        NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:filePath];
        [fileHandler seekToEndOfFile];
        [fileHandler writeData:[monitorLog dataUsingEncoding:NSUTF8StringEncoding]];
        [self saveMonitorLog];
    });
}

+ (NSString *)cpu_memoryLogPath
{
    struct tm* timeNow = [self getCurTime];
    NSArray* path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *nFilePath = [path objectAtIndex:0];
    nFilePath = [nFilePath stringByAppendingPathComponent:@"CPUMemoryUsage"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:nFilePath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:nFilePath withIntermediateDirectories:NO attributes:nil error:nil];
    }

    NSString *fileName = [NSString stringWithFormat:@"%d_%d_%d_CPU_Memory_Usage.log",timeNow->tm_year,timeNow->tm_mon,timeNow->tm_mday];
    nFilePath = [nFilePath stringByAppendingPathComponent:fileName];
    if (![[NSFileManager defaultManager] fileExistsAtPath:nFilePath]) {
        BOOL result = [[NSFileManager defaultManager] createFileAtPath:nFilePath contents:nil attributes:nil];
        NSLog(@"%d",result);
    }
    return nFilePath;
}

+ (struct tm*)getCurTime
{
    //時間格式
    struct timeval ticks;
    gettimeofday(&ticks, nil);
    time_t now;
    struct tm* timeNow;
    time(&now);
    timeNow = localtime(&now);
    timeNow->tm_gmtoff = ticks.tv_usec/1000;  //毫秒

    timeNow->tm_year += 1900;    //tm中的tm_year是從1900至今數(shù)
    timeNow->tm_mon  += 1;       //tm_mon范圍是0-11

    return timeNow;
}

+ (float)cpuUsage
{
    float cpu = cpu_usage();
    return cpu;
}

+ (float)memoryUsage
{
    vm_size_t memory = memory_usage();
    return memory / 1000.0 /1000.0;
}

vm_size_t memory_usage(void) {
    struct task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size);
    return (kerr == KERN_SUCCESS) ? info.resident_size : 0; // size in bytes
}

float cpu_usage()
{
    kern_return_t kr;
    task_info_data_t tinfo;
    mach_msg_type_number_t task_info_count;

    task_info_count = TASK_INFO_MAX;
    kr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)tinfo, &task_info_count);
    if (kr != KERN_SUCCESS) {
        return -1;
    }

    task_basic_info_t      basic_info;
    thread_array_t         thread_list;
    mach_msg_type_number_t thread_count;

    thread_info_data_t     thinfo;
    mach_msg_type_number_t thread_info_count;

    thread_basic_info_t basic_info_th;
    uint32_t stat_thread = 0; // Mach threads

    basic_info = (task_basic_info_t)tinfo;

    // get threads in the task
    kr = task_threads(mach_task_self(), &thread_list, &thread_count);
    if (kr != KERN_SUCCESS) {
        return -1;
    }
    if (thread_count > 0)
        stat_thread += thread_count;

    long tot_sec = 0;
    long tot_usec = 0;
    float tot_cpu = 0;
    int j;

    for (j = 0; j < thread_count; j++)
    {
        thread_info_count = THREAD_INFO_MAX;
        kr = thread_info(thread_list[j], THREAD_BASIC_INFO,
                         (thread_info_t)thinfo, &thread_info_count);
        if (kr != KERN_SUCCESS) {
            return -1;
        }

        basic_info_th = (thread_basic_info_t)thinfo;

        if (!(basic_info_th->flags & TH_FLAGS_IDLE)) {
            tot_sec = tot_sec + basic_info_th->user_time.seconds + basic_info_th->system_time.seconds;
            tot_usec = tot_usec + basic_info_th->user_time.microseconds + basic_info_th->system_time.microseconds;
            tot_cpu = tot_cpu + basic_info_th->cpu_usage / (float)TH_USAGE_SCALE * 100.0;
        }

    } // for each thread

    kr = vm_deallocate(mach_task_self(), (vm_offset_t)thread_list, thread_count * sizeof(thread_t));
    assert(kr == KERN_SUCCESS);

    return tot_cpu;
}

@end
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末衩椒,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子哮兰,更是在濱河造成了極大的恐慌毛萌,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,839評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件喝滞,死亡現(xiàn)場離奇詭異阁将,居然都是意外死亡,警方通過查閱死者的電腦和手機右遭,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,543評論 2 382
  • 文/潘曉璐 我一進店門做盅,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人窘哈,你說我怎么就攤上這事吹榴。” “怎么了宵距?”我有些...
    開封第一講書人閱讀 153,116評論 0 344
  • 文/不壞的土叔 我叫張陵腊尚,是天一觀的道長。 經(jīng)常有香客問我满哪,道長婿斥,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,371評論 1 279
  • 正文 為了忘掉前任哨鸭,我火速辦了婚禮民宿,結果婚禮上,老公的妹妹穿的比我還像新娘像鸡。我一直安慰自己活鹰,他們只是感情好,可當我...
    茶點故事閱讀 64,384評論 5 374
  • 文/花漫 我一把揭開白布只估。 她就那樣靜靜地躺著志群,像睡著了一般。 火紅的嫁衣襯著肌膚如雪蛔钙。 梳的紋絲不亂的頭發(fā)上锌云,一...
    開封第一講書人閱讀 49,111評論 1 285
  • 那天,我揣著相機與錄音吁脱,去河邊找鬼桑涎。 笑死彬向,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的攻冷。 我是一名探鬼主播娃胆,決...
    沈念sama閱讀 38,416評論 3 400
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼等曼!你這毒婦竟也來了里烦?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,053評論 0 259
  • 序言:老撾萬榮一對情侶失蹤禁谦,失蹤者是張志新(化名)和其女友劉穎招驴,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體枷畏,經(jīng)...
    沈念sama閱讀 43,558評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,007評論 2 325
  • 正文 我和宋清朗相戀三年虱饿,在試婚紗的時候發(fā)現(xiàn)自己被綠了拥诡。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,117評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡氮发,死狀恐怖渴肉,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情爽冕,我是刑警寧澤仇祭,帶...
    沈念sama閱讀 33,756評論 4 324
  • 正文 年R本政府宣布,位于F島的核電站颈畸,受9級特大地震影響乌奇,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜眯娱,卻給世界環(huán)境...
    茶點故事閱讀 39,324評論 3 307
  • 文/蒙蒙 一礁苗、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧徙缴,春花似錦试伙、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,315評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至穿剖,卻和暖如春蚤蔓,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背携御。 一陣腳步聲響...
    開封第一講書人閱讀 31,539評論 1 262
  • 我被黑心中介騙來泰國打工昌粤, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留既绕,地道東北人。 一個月前我還...
    沈念sama閱讀 45,578評論 2 355
  • 正文 我出身青樓涮坐,卻偏偏與公主長得像凄贩,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子袱讹,可洞房花燭夜當晚...
    茶點故事閱讀 42,877評論 2 345

推薦閱讀更多精彩內(nèi)容