iPhone の空きメモリ量や使用中のメモリ量を取得する
Instrumentsを使用せず、アプリ内から空きメモリ容量や使用中のメモリ容量を取得する方法です。
下記は空きメモリ容量を取得するサンプルです。
host_statistics()という関数を使用して、vm_statistics_data_t なる構造体を取得し、free_countという要素を出力しています。
#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; } natural_t mem_free = vm_stat.free_count * pagesize; return mem_free; }
(参考ページ)
natural_t は unsigned int型なので、%u というフォーマット指定子でNSLogなりUILabelに出力できます。
(フォーマット指定子一覧)
プライベートAPIを使用していないので審査もOKっぽいです。
vm_statictics 構造体の定義については、こちらにまとめられていました。
(http://d.hatena.ne.jp/It_lives_vainly/20090325/1237952703 より引用)
struct vm_statistics { natural_t free_count; // 空きメモリ容量(ページ数) natural_t active_count; // 現在使用中のメモリ容量(ページ数) natural_t inactive_count; // 現在非使用中のメモリ容量(ページ数) natural_t wire_count; // 現在固定中のメモリ容量(ページ数) natural_t zero_fill_count; // ゼロで埋まっているページ数(よくわからん) natural_t reactivations; // よくわからん natural_t pageins; // よくわからん natural_t pageouts; // よくわからん natural_t faults; // よくわからん natural_t cow_faults; // よくわからん natural_t lookups; // よくわからん natural_t hits; // よくわからん natural_t purgeable_count; // よくわからん natural_t purges; // よくわからん natural_t speculative_count; // よくわからん };
ここから取得できるメモリ量の単位は、ページ数なので byte 単位に変換するためにはページサイズを掛ける必要がある.
ちなみに、ここまで書いておいて host_statistics() とかが何者なのかよくわかっていないのですが、macのシステムコールとかいうものらしいです。
- macのシステムコールに関する情報(日本語)
- iOS Manual Pages(システムコールのドキュメント)
後日勉強します。