LoginSignup
94
95

More than 5 years have passed since last update.

Instrumentsを使用せず、プログラムから空きメモリ量や使用中のメモリ量、CPU負荷を取得する

Last updated at Posted at 2013-01-06

デバイスの空きメモリ量を取得する

host_statistics() を使用して、vm_statistics_data_t 構造体を取得します。その中の free_count という値が空きメモリ量を示しています。(この値の単位はページ数なので、単位をバイトに変換するためにはページサイズを掛ける必要があります。)

#import <mach/mach.h>

+ (unsigned int)getFreeMemory {

    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 (unsigned int)mem_free;
}        

アプリが使用しているメモリ量を取得する

タスク(いわゆるプロセス)の基本情報を取得するための関数 task_info() を使用して、task_basic_info 構造体を取得します。その中の resident_size という値が、物理メモリ使用量(バイト)を示しています。

struct task_basic_info basic_info;
mach_msg_type_number_t t_info_count = TASK_BASIC_INFO_COUNT;
kern_return_t status;

status = task_info(current_task(), TASK_BASIC_INFO,
                   (task_info_t)&basic_info, &t_info_count);

if (status != KERN_SUCCESS)
{
    NSLog(@"%s(): Error in task_info(): %s",
          __FUNCTION__, strerror(errno));
}

vm_size_t residentSize = basic_info.resident_size;

アプリの CPU 負荷を取得する

使用メモリ量を取得する際に用いた task_info() は第2引数に渡す値に応じて様々な情報を得ることができます。

task_info の man page

メモリ使用量を取得する場合には TASK_BASIC_INFO を指定しましたが、 TASK_THREAD_TIMES_INFO を指定することで実行中のスレッドの CPU 使用時間を取得することができます。

struct task_thread_times_info thread_info;
t_info_count = TASK_THREAD_TIMES_INFO_COUNT;
kern_return_t status;

status = task_info(current_task(), TASK_THREAD_TIMES_INFO,
                   (task_info_t)&thread_info, &t_info_count);

if (status != KERN_SUCCESS) {
    NSLog(@"%s(): Error in task_info(): %s",
          __FUNCTION__, strerror(errno));
    return;
}

uint64_t userTime   = tval2msec(thread_info.user_time);

上記コードで用いている tval2msec は time_value_t 型で得られた CPU 使用時間を msec に変換するためのマクロです。

#define tval2msec(tval) ((tval.seconds * 1000) + (tval.microseconds / 1000))

アプリ内でメモリ使用量と CPU 負荷をリアルタイム表示

上記の方法で取得したメモリ使用量と CPU 負荷、加えて View の数をアプリ内にリアルタイム表示するクラスを公開しています。よろしければご利用ください。

stats
http://d.hatena.ne.jp/shu223/20110428/1303930059

stats

94
95
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
94
95