Featured Post

Trie implementation in C

Getting CPU Parameters in Linux/Unix

Here is a simple implementation which reads the CPU information for a linux/unix kernel.
It uses the /proc/cpuinfo file for this purpose , which is a standard file present in the linux/unix system containing info about the CPU.

I have only extracted two parameters viz. CPU Clock Speed and CPU Cache Size.

There is a whole list of Parameters which can be fetched.
It can be seen by seeing the contents of /proc/cpuinfo file using by using following command on the terminal:

cat /proc/envinfo

#include <stdio.h>
#include <string.h>

/*This functions returns matched param's value in a buffer*/

char* get_param_val(char* buffer, char *param_name)
{
  char* match;
  match = strstr (buffer, param_name);
  if (match == NULL)
    return NULL;
  
  return match;
}

void get_cpu_params ()
{
  FILE* fp;
  char buffer[1024];
  size_t bytes_read;
  float clock_speed;
  int cache_size;
  char modelname[100];

  /* Read the entire contents of /proc/cpuinfo into the buffer. */
  fp = fopen ("/proc/cpuinfo", "r");
  bytes_read = fread (buffer, 1, sizeof (buffer), fp);
  fclose (fp);

  /* Return if read failed or if buffer isn't big enough. */
  if (bytes_read == 0 || bytes_read == sizeof (buffer))
    return ;
  
  buffer[bytes_read] = '\0';
  
  sscanf (get_param_val(buffer,"cpu MHz"), "cpu MHz : %f", &clock_speed);
  printf ("CPU clock speed: %f MHz\n",clock_speed);
  
  sscanf (get_param_val(buffer,"cache size"), "cache size : %d", &cache_size);
  printf ("CPU cache size: %d KB\n",cache_size);
  
}
int main ()
{
  get_cpu_params ();
  return 0;
}

Comments

  1. Hi this programs give sefmentattion fault at line 34

    ReplyDelete
  2. can you please post the solution

    ReplyDelete
  3. Hey I corrected the seg fault , i made a small mistake of writing CPU instead of cpu...used gdb to find it...thanks the mistake was silly but i learnt to use gdb i guess i someday had to...:P...trying to read other parameters...struggling with model name ...doesn't print a damn word...no seg faults though : D !!

    ReplyDelete

Post a Comment

Please post your valuable suggestions