Detect current CPU Clock Speed Programmatically on OS X?

人盡茶涼 提交于 2019-12-03 00:17:15
Yevgeni

Try this tool called "Intel Power Gadget". It displays IA frequency and IA power in real time.

http://software.intel.com/sites/default/files/article/184535/intel-power-gadget-2.zip

You can query the CPU speed easily via sysctl, either by command line:

sysctl hw.cpufrequency

Or via C:

#include <stdio.h>
#include <sys/types.h>
#include <sys/sysctl.h>

int main() {
        int mib[2];
        unsigned int freq;
        size_t len;

        mib[0] = CTL_HW;
        mib[1] = HW_CPU_FREQ;
        len = sizeof(freq);
        sysctl(mib, 2, &freq, &len, NULL, 0);

        printf("%u\n", freq);

        return 0;
}

Since it's an Intel processor, you could always use RDTSC. That's an assembler instruction that returns the current cycle counter — a 64bit counter that increments every cycle. It'd be a little approximate but e.g.

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

uint64_t rdtsc(void)
{
    uint32_t ret0[2];
    __asm__ __volatile__("rdtsc" : "=a"(ret0[0]), "=d"(ret0[1]));
    return ((uint64_t)ret0[1] << 32) | ret0[0];
}

int main(int argc, const char * argv[])
{
    uint64_t startCount = rdtsc();
    sleep(1);
    uint64_t endCount = rdtsc();

    printf("Clocks per second: %llu", endCount - startCount);

    return 0;
}

Output 'Clocks per second: 2002120630' on my 2Ghz MacBook Pro.

There is a kernel extension written by "flAked" which logs the cpu p-state to the kernel log. http://www.insanelymac.com/forum/index.php?showtopic=258612

maybe you could contact him for the code.

This seems to work correctly on OSX. However, it doesn't work on Linux, where sysctl is deprecated and KERN_CLOCKRATE is undefined.

#include <sys/sysctl.h>
#include <sys/time.h>

  int mib[2];
  size_t len;
  mib[0] = CTL_KERN;
  mib[1] = KERN_CLOCKRATE;
  struct clockinfo clockinfo;
  len = sizeof(clockinfo);
  int result = sysctl(mib, 2, &clockinfo, &len, NULL, 0);
  assert(result != -1);
  log_trace("clockinfo.hz: %d\n", clockinfo.hz);
  log_trace("clockinfo.tick: %d\n", clockinfo.tick);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!