How to check CPU name, model, speed on Windows/Linux C?

六眼飞鱼酱① 提交于 2019-12-08 06:40:32

问题


I would like to get some infos with C about hardware:

  1. how many CPU's I have
  2. how many cores have each of them
  3. how many logical cores have every core in every CPU
  4. CPU name + model
  5. CPU speed + frequency
  6. CPU architecture (x86, x64)

I know that on Linux-like OS I can parse /proc/cpuinfo but since its not an ordinary file, I think its unsafe. Saw this answer on SO but it doesnt give me EVERY info I need. Should I call cat /proc/cpuinfo > file.txt and then parse file.txt? I know about cpuid.h (Im using GCC) but ca't find any doc about this header (anyway - is it a good idea to use it?)


回答1:


Linux procfs's fake files can behave very problematically. The kernel falsely reports them as regular files, but they don't behave as regular files are required to on a conforming POSIX system. For an example, see http://www.openwall.com/lists/musl/2013/05/05/9. I suspect you've heard similar reports and this is where your concern is coming from.

With that said, as far as I know, all of the bad behavior of the fake "regular files" in /proc pertains only to writing. For reading they should behave sufficiently similar to actual regular files that you can just read them however you like and not worry about it.




回答2:


For Windows, you'll want the GetSystemInfo function; Microsoft has an example. On Linux, /proc/cpuinfo is perfectly "safe", whatever that means, but there's already an answer to this question.




回答3:


If you care only about intel-compatible CPUs you could use the assembler instruction

cpuid

either as inline asm or as a separate asm object file.

For example, to check the vendor you would use function 0:

xor eax, eax  ; load eax with function 0
cpuid         ; call cpuid

Now the vendor ID is located in the registers ebx, ecx, edx. Similar functions exist to read all other information.

For more information read this



来源:https://stackoverflow.com/questions/18592580/how-to-check-cpu-name-model-speed-on-windows-linux-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!