首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在C中获取CPU和内存使用率?(在Linux系统中)

在Linux系统中,可以使用以下方法来获取CPU和内存使用率:

  1. 获取CPU使用率:
    • 使用/proc/stat文件:该文件提供了有关系统CPU的统计信息。可以读取该文件并解析其中的数据来计算CPU使用率。
    • 使用top命令:在终端中运行top命令,然后按下1键可以查看每个CPU核心的使用率。
  • 获取内存使用率:
    • 使用/proc/meminfo文件:该文件包含了有关系统内存的信息,包括总内存、可用内存、已使用内存等。可以读取该文件并解析其中的数据来计算内存使用率。
    • 使用free命令:在终端中运行free命令,可以查看系统的内存使用情况,包括总内存、已使用内存、可用内存等。

以下是一个示例代码,演示如何在C语言中获取CPU和内存使用率:

代码语言:txt
复制
#include <stdio.h>
#include <stdlib.h>

// 获取CPU使用率
float get_cpu_usage() {
    FILE* file = fopen("/proc/stat", "r");
    if (file == NULL) {
        perror("Failed to open /proc/stat");
        exit(1);
    }

    unsigned long long user, nice, system, idle;
    if (fscanf(file, "cpu %llu %llu %llu %llu", &user, &nice, &system, &idle) != 4) {
        perror("Failed to read CPU usage from /proc/stat");
        exit(1);
    }

    fclose(file);

    unsigned long long total = user + nice + system + idle;
    unsigned long long used = total - idle;
    return (float)used / total * 100.0;
}

// 获取内存使用率
float get_memory_usage() {
    FILE* file = fopen("/proc/meminfo", "r");
    if (file == NULL) {
        perror("Failed to open /proc/meminfo");
        exit(1);
    }

    unsigned long long total, available;
    if (fscanf(file, "MemTotal: %llu kB\nMemAvailable: %llu kB", &total, &available) != 2) {
        perror("Failed to read memory usage from /proc/meminfo");
        exit(1);
    }

    fclose(file);

    unsigned long long used = total - available;
    return (float)used / total * 100.0;
}

int main() {
    float cpu_usage = get_cpu_usage();
    float memory_usage = get_memory_usage();

    printf("CPU Usage: %.2f%%\n", cpu_usage);
    printf("Memory Usage: %.2f%%\n", memory_usage);

    return 0;
}

请注意,以上代码仅适用于Linux系统,并且需要以root权限运行。在实际应用中,可能需要根据具体情况进行适当的修改和优化。

腾讯云相关产品和产品介绍链接地址:

  • 腾讯云计算产品:https://cloud.tencent.com/product
  • 腾讯云服务器(CVM):https://cloud.tencent.com/product/cvm
  • 腾讯云云数据库(TencentDB):https://cloud.tencent.com/product/cdb
  • 腾讯云云原生应用引擎(Tencent Cloud Native Application Engine):https://cloud.tencent.com/product/tcnae
  • 腾讯云音视频处理(VOD):https://cloud.tencent.com/product/vod
  • 腾讯云人工智能(AI):https://cloud.tencent.com/product/ai
  • 腾讯云物联网(IoT):https://cloud.tencent.com/product/iot
  • 腾讯云移动开发(Mobile):https://cloud.tencent.com/product/mobile
  • 腾讯云对象存储(COS):https://cloud.tencent.com/product/cos
  • 腾讯云区块链(Blockchain):https://cloud.tencent.com/product/baas
  • 腾讯云元宇宙(Metaverse):https://cloud.tencent.com/product/metaverse
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

11分33秒

061.go数组的使用场景

9分12秒

运维实践-在ESXI中使用虚拟机进行Ubuntu22.04-LTS发行版操作系统与密码忘记重置

1分56秒

园区视频监控智能分析系统

2分5秒

AI行为识别视频监控系统

14分35秒

Windows系统未激活或key不合适,导致内存只能用到2G

1时8分

TDSQL安装部署实战

1分56秒

智慧加油站AI智能视频分析系统

44分43秒

Julia编程语言助力天气/气候数值模式

26分40秒

晓兵技术杂谈2-intel_daos用户态文件系统io路径_dfuse_io全路径_io栈_c语言

3.4K
2分29秒

基于实时模型强化学习的无人机自主导航

1分1秒

多通道振弦传感器无线采集仪在工程监测中是否好用?

56秒

无线振弦采集仪应用于桥梁安全监测

领券