web-dev-qa-db-ja.com

C ++を使用して実行時にメモリ使用量を取得する方法は?

プログラムの実行時にmem usage VIRTおよびRESを取得して表示する必要があります。

私が今まで試したこと:

getrusage( http://linux.die.net/man/2/getrusage

int who = RUSAGE_SELF; 
struct rusage usage; 
int ret; 

ret=getrusage(who,&usage);

cout<<usage.ru_maxrss;

しかし、私は常に0を取得します。

76
frenk

Linuxでは、ioctl()ソリューションが見つかりませんでした。このアプリケーションでは、/ proc/pidのファイルの読み取りに基づいて一般的なユーティリティルーチンをコーディングしました。異なる結果を与えるこれらのファイルが多数あります。解決策は次のとおりです(質問にはC++というタグが付けられ、C++コンストラクトを使用してI/Oを処理しましたが、必要に応じてC I/Oルーチンに簡単に適応できるはずです)。

#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>

//////////////////////////////////////////////////////////////////////////////
//
// process_mem_usage(double &, double &) - takes two doubles by reference,
// attempts to read the system-dependent data for a process' virtual memory
// size and resident set size, and return the results in KB.
//
// On failure, returns 0.0, 0.0

void process_mem_usage(double& vm_usage, double& resident_set)
{
   using std::ios_base;
   using std::ifstream;
   using std::string;

   vm_usage     = 0.0;
   resident_set = 0.0;

   // 'file' stat seems to give the most reliable results
   //
   ifstream stat_stream("/proc/self/stat",ios_base::in);

   // dummy vars for leading entries in stat that we don't care about
   //
   string pid, comm, state, ppid, pgrp, session, tty_nr;
   string tpgid, flags, minflt, cminflt, majflt, cmajflt;
   string utime, stime, cutime, cstime, priority, Nice;
   string O, itrealvalue, starttime;

   // the two fields we want
   //
   unsigned long vsize;
   long rss;

   stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
               >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
               >> utime >> stime >> cutime >> cstime >> priority >> Nice
               >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest

   stat_stream.close();

   long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
   vm_usage     = vsize / 1024.0;
   resident_set = rss * page_size_kb;
}

int main()
{
   using std::cout;
   using std::endl;

   double vm, rss;
   process_mem_usage(vm, rss);
   cout << "VM: " << vm << "; RSS: " << rss << endl;
}
71
Don Wakefield

David Robert Nadea は、自己完結型の良い プロセス常駐セットサイズ(物理メモリ使用量)を取得するマルチプラットフォームC関数 を彼のWebサイトに配置しました。

/*
 * Author:  David Robert Nadeau
 * Site:    http://NadeauSoftware.com/
 * License: Creative Commons Attribution 3.0 Unported License
 *          http://creativecommons.org/licenses/by/3.0/deed.en_US
 */

#if defined(_WIN32)
#include <windows.h>
#include <psapi.h>

#Elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__Apple__) && defined(__MACH__))
#include <unistd.h>
#include <sys/resource.h>

#if defined(__Apple__) && defined(__MACH__)
#include <mach/mach.h>

#Elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__Sun__) || defined(__Sun) || defined(Sun) && (defined(__SVR4) || defined(__svr4__)))
#include <fcntl.h>
#include <procfs.h>

#Elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
#include <stdio.h>

#endif

#else
#error "Cannot define getPeakRSS( ) or getCurrentRSS( ) for an unknown OS."
#endif





/**
 * Returns the peak (maximum so far) resident set size (physical
 * memory use) measured in bytes, or zero if the value cannot be
 * determined on this OS.
 */
size_t getPeakRSS( )
{
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.PeakWorkingSetSize;

#Elif (defined(_AIX) || defined(__TOS__AIX__)) || (defined(__Sun__) || defined(__Sun) || defined(Sun) && (defined(__SVR4) || defined(__svr4__)))
    /* AIX and Solaris ------------------------------------------ */
    struct psinfo psinfo;
    int fd = -1;
    if ( (fd = open( "/proc/self/psinfo", O_RDONLY )) == -1 )
        return (size_t)0L;      /* Can't open? */
    if ( read( fd, &psinfo, sizeof(psinfo) ) != sizeof(psinfo) )
    {
        close( fd );
        return (size_t)0L;      /* Can't read? */
    }
    close( fd );
    return (size_t)(psinfo.pr_rssize * 1024L);

#Elif defined(__unix__) || defined(__unix) || defined(unix) || (defined(__Apple__) && defined(__MACH__))
    /* BSD, Linux, and OSX -------------------------------------- */
    struct rusage rusage;
    getrusage( RUSAGE_SELF, &rusage );
#if defined(__Apple__) && defined(__MACH__)
    return (size_t)rusage.ru_maxrss;
#else
    return (size_t)(rusage.ru_maxrss * 1024L);
#endif

#else
    /* Unknown OS ----------------------------------------------- */
    return (size_t)0L;          /* Unsupported. */
#endif
}





/**
 * Returns the current resident set size (physical memory use) measured
 * in bytes, or zero if the value cannot be determined on this OS.
 */
size_t getCurrentRSS( )
{
#if defined(_WIN32)
    /* Windows -------------------------------------------------- */
    PROCESS_MEMORY_COUNTERS info;
    GetProcessMemoryInfo( GetCurrentProcess( ), &info, sizeof(info) );
    return (size_t)info.WorkingSetSize;

#Elif defined(__Apple__) && defined(__MACH__)
    /* OSX ------------------------------------------------------ */
    struct mach_task_basic_info info;
    mach_msg_type_number_t infoCount = MACH_TASK_BASIC_INFO_COUNT;
    if ( task_info( mach_task_self( ), MACH_TASK_BASIC_INFO,
        (task_info_t)&info, &infoCount ) != KERN_SUCCESS )
        return (size_t)0L;      /* Can't access? */
    return (size_t)info.resident_size;

#Elif defined(__linux__) || defined(__linux) || defined(linux) || defined(__gnu_linux__)
    /* Linux ---------------------------------------------------- */
    long rss = 0L;
    FILE* fp = NULL;
    if ( (fp = fopen( "/proc/self/statm", "r" )) == NULL )
        return (size_t)0L;      /* Can't open? */
    if ( fscanf( fp, "%*s%ld", &rss ) != 1 )
    {
        fclose( fp );
        return (size_t)0L;      /* Can't read? */
    }
    fclose( fp );
    return (size_t)rss * (size_t)sysconf( _SC_PAGESIZE);

#else
    /* AIX, BSD, Solaris, and Unknown OS ------------------------ */
    return (size_t)0L;          /* Unsupported. */
#endif
}

使用法

size_t currentSize = getCurrentRSS( );
size_t peakSize    = getPeakRSS( );

詳細については、Webサイトを確認してください。また、 システムの物理メモリサイズを取得する関数 も提供しています。

45
pepper_chico

古い:

maxrssは、プロセスで使用可能な最大メモリを示します。 0は、プロセスに制限がないことを意味します。おそらく必要なのは、非共有データの使用ru_idrss

新規:カーネルがほとんどの値を満たさないため、上記は実際には機能しないようです。動作するのは、procから情報を取得することです。ただし、自分で解析する代わりに、次のようにlibproc(procpsの一部)を使用する方が簡単です。

// getrusage.c
#include <stdio.h>
#include <proc/readproc.h>

int main() {
  struct proc_t usage;
  look_up_our_self(&usage);
  printf("usage: %lu\n", usage.vsize);
}

gcc -o getrusage getrusage.c -lproc "

19
Paul de Vrieze

Linuxでは、ランタイムコスト(デバッグ用)に余裕がある場合は、massifツールでvalgrindを使用できます。

http://valgrind.org/docs/manual/ms-manual.html

重いですが、とても便利です。

9

既存の答えは正しい値を取得する方法には適していますが、少なくともgetrusageが機能しない理由を説明できます。

man 2 getrusage:

上記の構造体[rusage]は、BSD 4.3 Renoから取られました。 Linuxではすべてのフィールドが意味があるわけではありません。現在(Linux 2.4、2.6)、フィールドru_utime、ru_stime、ru_minflt、ru_majflt、およびru_nswapのみが維持されています。

6
jmanning2k

Don Wakefieldメソッドのよりエレガントな方法:

#include <iostream>
#include <fstream>

using namespace std;

int main(){

    int tSize = 0, resident = 0, share = 0;
    ifstream buffer("/proc/self/statm");
    buffer >> tSize >> resident >> share;
    buffer.close();

    long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
    double rss = resident * page_size_kb;
    cout << "RSS - " << rss << " kB\n";

    double shared_mem = share * page_size_kb;
    cout << "Shared Memory - " << shared_mem << " kB\n";

    cout << "Private Memory - " << rss - shared_mem << "kB\n";
    return 0;
}
5
Qsiris

あなたの方法に加えて
system psコマンドを呼び出して、その出力からメモリ使用量を取得できます。
または/ proc/pidから情報を読み取ります(PIOCPSINFO構造体を参照)

3
bayda

少ない変数を使用したDon Wのソリューションに基づいています。

void process_mem_usage(double& vm_usage, double& resident_set)
{
    vm_usage     = 0.0;
    resident_set = 0.0;

    // the two fields we want
    unsigned long vsize;
    long rss;
    {
        std::string ignore;
        std::ifstream ifs("/proc/self/stat", std::ios_base::in);
        ifs >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
                >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore >> ignore
                >> ignore >> ignore >> vsize >> rss;
    }

    long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
    vm_usage = vsize / 1024.0;
    resident_set = rss * page_size_kb;
}
1

私はそれをするために他の方法を使用しています、そしてそれは現実的に聞こえます。私がやっていることは、getpid()関数によってプロセスのPIDを取得し、/ proc/pid/statファイルを使用することです。 statファイルの23列目はvmsizeだと思います(Donの投稿をご覧ください)。コード内の必要な場所であれば、ファイルからvmsizeを読み取ることができます。コードのスニペットがどれだけメモリを使用するのか疑問に思う場合は、そのスニペットの前と後の1回ずつそのファイルを読み取り、それらを互いに減算することができます。

1
Amir

使用される最大メモリを測定するLinuxアプリを探していました。 valgrindは優れたツールですが、必要以上に多くの情報を提供してくれました。 tstime は、私が見つけることができる最高のツールのようでした。 「ハイウォーター」メモリ使用量(RSSおよび仮想)を測定します。 この回答 を参照してください。

0
jtpereyda