素槿
Published on 2025-08-22 / 6 Visits
0

C语言获取系统和CPU信息

原理

使用 #include <sys/sysinfo.h>文件中的接口读取系统信息。

代码

#include <stdio.h>
#include <sys/sysinfo.h>
int main(int argc, char const* argv[])
{
    printf("cpu processors %d, available cores %d.\n", get_nprocs_conf(),
           get_nprocs());
    return 0;
}

输出:

$ g++ main.cc 
$ ./a.out 
cpu processors 8, available cores 8.

查看进程运行在哪个CPU核心,哪个NUMA节点

#include <sched.h>
#include <iostream>
using namespace std;

int main(int argc, char const* argv[])
{
    unsigned int cpu, node;
    getcpu(&cpu, &node);
    cout << "cpu=" << cpu << " node=" << node << endl;
    // cpu=4 node=0 , 当前进程运行在哪个CPU核心,哪个NUMA节点
    return 0;
}

输出:

$ g++ main.cc 
$ ./a.out 
cpu=2 node=0

其他

头文件 #include <sys/sysinfo.h>中的其他接口

#ifndef _SYS_SYSINFO_H
#define _SYS_SYSINFO_H	1

#include <features.h>

/* Get sysinfo structure from kernel header.  */
#include <linux/kernel.h>

__BEGIN_DECLS

/* Returns information on overall system statistics.  */
extern int sysinfo (struct sysinfo *__info) __THROW;


/* Return number of configured processors.  */
extern int get_nprocs_conf (void) __THROW;

/* Return number of available processors.  */
extern int get_nprocs (void) __THROW;


/* Return number of physical pages of memory in the system.  */
extern long int get_phys_pages (void) __THROW;

/* Return number of available physical pages of memory in the system.  */
extern long int get_avphys_pages (void) __THROW;

__END_DECLS

#endif	/* sys/sysinfo.h */
struct sysinfo {
	__kernel_long_t uptime;		/* Seconds since boot */
	__kernel_ulong_t loads[3];	/* 1, 5, and 15 minute load averages */
	__kernel_ulong_t totalram;	/* Total usable main memory size */
	__kernel_ulong_t freeram;	/* Available memory size */
	__kernel_ulong_t sharedram;	/* Amount of shared memory */
	__kernel_ulong_t bufferram;	/* Memory used by buffers */
	__kernel_ulong_t totalswap;	/* Total swap space size */
	__kernel_ulong_t freeswap;	/* swap space still available */
	__u16 procs;		   	/* Number of current processes */
	__u16 pad;		   	/* Explicit padding for m68k */
	__kernel_ulong_t totalhigh;	/* Total high memory size */
	__kernel_ulong_t freehigh;	/* Available high memory size */
	__u32 mem_unit;			/* Memory unit size in bytes */
	char _f[20-2*sizeof(__kernel_ulong_t)-sizeof(__u32)];	/* Padding: libc5 uses this.. */
};