首页
学习
活动
专区
工具
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
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券