How to determine CPU and memory consumption from inside a process?

后端 未结 9 1710
被撕碎了的回忆
被撕碎了的回忆 2020-11-21 11:28

I once had the task of determining the following performance parameters from inside a running application:

  • Total virtual memory available
  • Virtual memo
9条回答
  •  半阙折子戏
    2020-11-21 12:18

    QNX

    Since this is like a "wikipage of code" I want to add some code from the QNX Knowledge base (note: this is not my work, but I checked it and it works fine on my system):

    How to get CPU usage in %: http://www.qnx.com/support/knowledgebase.html?id=50130000000P9b5

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    #define MAX_CPUS 32
    
    static float Loads[MAX_CPUS];
    static _uint64 LastSutime[MAX_CPUS];
    static _uint64 LastNsec[MAX_CPUS];
    static int ProcFd = -1;
    static int NumCpus = 0;
    
    
    int find_ncpus(void) {
        return NumCpus;
    }
    
    int get_cpu(int cpu) {
        int ret;
        ret = (int)Loads[ cpu % MAX_CPUS ];
        ret = max(0,ret);
        ret = min(100,ret);
        return( ret );
    }
    
    static _uint64 nanoseconds( void ) {
        _uint64 sec, usec;
        struct timeval tval;
        gettimeofday( &tval, NULL );
        sec = tval.tv_sec;
        usec = tval.tv_usec;
        return( ( ( sec * 1000000 ) + usec ) * 1000 );
    }
    
    int sample_cpus( void ) {
        int i;
        debug_thread_t debug_data;
        _uint64 current_nsec, sutime_delta, time_delta;
        memset( &debug_data, 0, sizeof( debug_data ) );
        
        for( i=0; inum_cpu;
                /* Get a starting point for the comparisons */
                for( i=0; i

    How to get the free (!) memory: http://www.qnx.com/support/knowledgebase.html?id=50130000000mlbx

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main( int argc, char *argv[] ){
        struct stat statbuf;
        paddr_t freemem;
        stat( "/proc", &statbuf );
        freemem = (paddr_t)statbuf.st_size;
        printf( "Free memory: %d bytes\n", freemem );
        printf( "Free memory: %d KB\n", freemem / 1024 );
        printf( "Free memory: %d MB\n", freemem / ( 1024 * 1024 ) );
        return 0;
    } 
    

提交回复
热议问题