获取cpu频率的代码

3630阅读 0评论2014-06-26 zealoussnow
分类:LINUX

taskset是linux自带的一个命令,可用来将进程绑定到指定CPU
相关的函数有: sched_setaffinity, CPU_CLR, CPU_ISSET, CPU_SET, CPU_ZERO

  1. // cpufreq库可在/usr/lib目录下找到
  2. // 编译: g++ -g -o x x.cpp -lcpufreq
  3. // 需要以root用户执行以下代码
  4. //#include <cpufreq.h>
  5. #include <stdio.h>
  6. #include <sys/sysinfo.h> // get_nprocs

  7. // 如果不存在/usr/include/cpufreq.h
  8. #ifndef _CPUFREQ_H
  9.     extern "C" int cpufreq_cpu_exists(unsigned int cpu);
  10.     extern "C" unsigned long cpufreq_get_freq_kernel(unsigned int cpu);
  11.     extern "C" unsigned long cpufreq_get_freq_hardware(unsigned int cpu);
  12.     extern "C" int cpufreq_get_hardware_limits(unsigned int cpu, unsigned long *min, unsigned long *max);
  13. #endif

  14. int main()
  15. {
  16.     // 取得cpu core的个数,proc是processor的意思
  17.     int nprocs = get_nprocs();
  18.     for (int i=0; i<nprocs; ++i)
  19.     {
  20.         if (0 == cpufreq_cpu_exists(i))
  21.         {
  22.             unsigned long min_freq = 0;
  23.             unsigned long max_freq = 0;
  24.             cpufreq_get_hardware_limits(i, &min_freq, &max_freq);

  25.             printf("cpu[%d]:\n", i);
  26.             printf("min_freq: %lu, max_freq: %lu\n", min_freq, max_freq);
  27.             printf("kernel freq: %lu, hardware freq: %lu\n", cpufreq_get_freq_kernel(i), cpufreq_get_freq_hardware(i));
  28.             printf("\n");
  29.         }
  30.     }

  31.     return 0;
  32. }


上一篇:devhelp的使用小结
下一篇:没有了