简体   繁体   中英

Monitor memory usage in an iphone app?

是否可以监控应用消耗的内存量?

Actually, it's probably more important you know how much memory is free, rather than how much your app is using. Here's some code to do that:

#import <mach/mach.h>
#import <mach/mach_host.h>

+(natural_t) get_free_memory {
    mach_port_t host_port;
    mach_msg_type_number_t host_size;
    vm_size_t pagesize;
    host_port = mach_host_self();
    host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
    host_page_size(host_port, &pagesize);
    vm_statistics_data_t vm_stat;

    if (host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size) != KERN_SUCCESS) {
        NSLog(@"Failed to fetch vm statistics");
        return 0;
    }

    /* Stats in bytes */
    natural_t mem_free = vm_stat.free_count * pagesize;
    return mem_free;
}

Yes. In Xcode, open your project and choose Run > Run with Performance Tool > Allocations . This will start an application called Instruments, which can be used to analyze your app. In that specific case it will record all object allocations which gives you a good overview of your memory footprint. You can use this with both, the iOS Simulator and an actual device. You should prefer to analyze the app while running on an iOS device to get optimal results.

Instruments can do a lot more to help you optimize your apps, so you should give the Instruments User Guide a closer look.

You can use Instruments. It is provided with iOS SDK.
It is more accurate with a device than the simulator...

Launch it, choose a type of monitoring (Allocation, Leaks, Activity Monitor), choose process and target to monitor and then click on the record button.
Clicking on this button, the app opens by itself.

When you've finished, click on the stop button to stop monitoring.

You can find more informations about this program here: About Instruments

You can check your running memory here. Wont give details of what is consuming but a good total amount of memory.

在此输入图像描述

If you have an apple developer account check out the current WWDC about instruments and optimizing memory on ios. It is really worth seeing if you which to quickly understand how instruments are working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM