linux下使用C语言如何获得CPU的主频

本文介绍了两种方法来获取Linux系统的CPU频率:一种是通过读取/proc/cpuinfo文件并解析其中的信息;另一种是利用时间戳计数器(RDTSC)进行简单的性能测试,从而估算出CPU的工作频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://blog.csdn.net/jesun/archive/2008/04/05/2252679.aspx

#include<stdio.h>
#include<stdlib.h>
int main(){
        FILE *fp;
        char str[81];
        memset(str,0,81);
        fp=popen("cat /proc/cpuinfo|grep cpu\\ MHz|sed -e 's/.*:[^0-9]//'","r");
        if(fp<0){
                printf("无法读取 CPU主频信息\n");
                exit(1);
        }
        fgets(str,80,fp);
        fclose(fp);
        double spd=atof(str);
        printf("您 CPU主频是%fMHz\n",spd);
        exit(0);
}

#include <stdio.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/time.h>

static int64_t rdtsc(void)
{
    unsigned int i, j;
    asm volatile (" rdtsc" : "=a"(i), "=d"(j) : );
    return ((int64_t)j<<32) + (int64_t)i;
}
int main()
{
    int64_t tsc_start, tsc_end;
    struct timeval tv_start, tv_end;
    int usec_delay;

    tsc_start = rdtsc();
    gettimeofday(&tv_start, NULL);
    usleep(100000);
    tsc_end = rdtsc();
    gettimeofday(&tv_end, NULL);

    usec_delay = 1000000 * (tv_end.tv_sec - tv_start.tv_sec)
        + (tv_end.tv_usec - tv_start.tv_usec);

    printf(" cpu MHz\t\t: %.3f\n",
           (double)(tsc_end-tsc_start) / usec_delay);
}


cat /proc/cpuinf | awk -F: 'BEGIN{printf " cpu frequency is :"}{if($1~/ cpu /)print $2}'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值