欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

IOS 调试小工具显示内存和CPU 使用率

程序员文章站 2022-04-17 22:08:25
...

关于网络上下行的有点问题,不准确
CPU 和内存 基本是准确的,有需求的可以添加FPS 相关的

#import <Foundation/Foundation.h>

@interface SyStemSourceTool : NSObject
+(instancetype)sharedInstance;
-(void)startShowSystemState;
@end
#import "SyStemSourceTool.h"
#import <mach/mach.h>
#import <sys/time.h>


#import <net/if_var.h>
#import <ifaddrs.h>
#import <sys/socket.h>
#include <arpa/inet.h>

#include <net/if.h>
@interface SyStemSourceTool()
@property (nonatomic, assign) NSTimeInterval  timeInterval;
@property(nonatomic,strong)UILabel *label;
@end
@implementation SyStemSourceTool
+(instancetype)sharedInstance{
    static SyStemSourceTool *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SyStemSourceTool alloc]init];
    });
    return instance;
}


- (void)startShowSystemState
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        float cpuUsage = [SyStemSourceTool cpuUsage];
        float memoryUsage = [SyStemSourceTool memoryUsage]/2;
        float net_m =[SyStemSourceTool getInterfaceBytes]/1024/1024;
        //struct tm* timeNow = [SyStemSourceTool getCurTime];
        NSString *monitorLog = [NSString stringWithFormat:@"cpu:%.2f || memery:%.2f || net:%.2f",
                                cpuUsage,
                                memoryUsage,net_m];
        NSLog(@"%@",monitorLog);
        [self showSystemSourceDetail:monitorLog];
        [self startShowSystemState];
    });
}




+ (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
}
//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;
}
//网络上下行,感觉有点问题
+ (long long) getInterfaceBytes
{
    struct ifaddrs *ifa_list = 0, *ifa;
    if (getifaddrs(&ifa_list) == -1)
    {
        return 0;
    }

    uint32_t iBytes = 0;
    uint32_t oBytes = 0;

    for (ifa = ifa_list; ifa; ifa = ifa->ifa_next)
    {
        if (AF_LINK != ifa->ifa_addr->sa_family)
            continue;

        if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))
            continue;

        if (ifa->ifa_data == 0)
            continue;

        /* Not a loopback device. */
        if (strncmp(ifa->ifa_name, "lo", 2))
        {
            struct if_data *if_data = (struct if_data *)ifa->ifa_data;

            iBytes += if_data->ifi_ibytes;
            oBytes += if_data->ifi_obytes;
        }
    }
    freeifaddrs(ifa_list);

    NSLog(@"\n[getInterfaceBytes-Total]%d,%d",iBytes,oBytes);
    return iBytes + oBytes;
}
//显示控件,可以自己添加Release 隐藏方法
-(void)showSystemSourceDetail:(NSString*)message{
    if (!_label) {
        UIWindow * window = [UIApplication sharedApplication].keyWindow;
        UIView *showview =  [[UIView alloc]init];
        showview.backgroundColor = [UIColor grayColor];
        showview.frame = CGRectMake(1, 1, 1, 1);
        showview.alpha = 1.0f;
        showview.layer.cornerRadius = 5.0f;
        showview.layer.masksToBounds = YES;
        [window addSubview:showview];
        CGSize sizeRect =[SyUtils getAttributeSizeWithText:message fontSize:18];
        [showview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(sizeRect.width+160);
            make.height.mas_equalTo(sizeRect.height+10);
            //        make.centerX.mas_equalTo(window.mas_centerX);
            //        make.centerY.mas_equalTo(window.mas_centerY);
            make.right.mas_equalTo(window.mas_right);
            make.top.mas_equalTo(window.mas_top);
        }];
        _label = [[UILabel alloc]init];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
        paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;

        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:10.f],
                                     NSParagraphStyleAttributeName:paragraphStyle.copy};

        //CGSize sizeRect =[SyUtils getAttributeSizeWithText:message fontSize:15];
        //    CGSize labelSize = [message boundingRectWithSize:CGSizeMake(207, 999)
        //                                             options:NSStringDrawingUsesLineFragmentOrigin
        //                                          attributes:attributes context:nil].size;
        CGSize labelSize = [message boundingRectWithSize:CGSizeMake(sizeRect.width+150, sizeRect.height+10)
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:attributes context:nil].size;

        self.label.frame = CGRectMake(10, 5, labelSize.width +150, labelSize.height);
        self.label.text = message;
        self.label.textColor = [UIColor whiteColor];
        self.label.textAlignment = NSTextAlignmentLeft;
        self.label.backgroundColor = [UIColor clearColor];
        self.label.font = [UIFont boldSystemFontOfSize:15];
        [showview addSubview:self.label];
        [self.label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(sizeRect.width+150);
            make.centerX.mas_equalTo(showview.mas_centerX);
            make.centerY.mas_equalTo(showview.mas_centerY);
        }];
        showview.center = window.center;
    }
    _label.text = message;
//    [UIView animateWithDuration:time animations:^{
//        showview.alpha = 0;
//    } completion:^(BOOL finished) {
//        [showview removeFromSuperview];
//    }];
}
相关标签: 调试工具