| 1 |
/*********************************************************************** |
| 2 |
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * |
| 3 |
* Copyright (C) 2001 by New Riders Publishing * |
| 4 |
* See COPYRIGHT for license information. * |
| 5 |
***********************************************************************/ |
| 6 |
|
| 7 |
#include <stdio.h> |
| 8 |
#include <string.h> |
| 9 |
|
| 10 |
/* Returns the clock speed of the system's CPU in MHz, as reported by |
| 11 |
/proc/cpuinfo. On a multiprocessor machine, returns the speed of |
| 12 |
the first CPU. On error returns zero. */ |
| 13 |
|
| 14 |
float get_cpu_clock_speed () |
| 15 |
{ |
| 16 |
FILE* fp; |
| 17 |
char buffer[1024]; |
| 18 |
size_t bytes_read; |
| 19 |
char* match; |
| 20 |
float clock_speed; |
| 21 |
|
| 22 |
/* Read the entire contents of /proc/cpuinfo into the buffer. */ |
| 23 |
fp = fopen ("/proc/cpuinfo", "r"); |
| 24 |
bytes_read = fread (buffer, 1, sizeof (buffer), fp); |
| 25 |
fclose (fp); |
| 26 |
/* Bail if read failed or if buffer isn't big enough. */ |
| 27 |
if (bytes_read == 0 || bytes_read == sizeof (buffer)) |
| 28 |
return 0; |
| 29 |
/* NUL-terminate the text. */ |
| 30 |
buffer[bytes_read] = '\0'; |
| 31 |
/* Locate the line that starts with "cpu MHz". */ |
| 32 |
match = strstr (buffer, "cpu MHz"); |
| 33 |
if (match == NULL) |
| 34 |
return 0; |
| 35 |
/* Parse the line to extrace the clock speed. */ |
| 36 |
sscanf (match, "cpu MHz : %f", &clock_speed); |
| 37 |
return clock_speed; |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
int main () |
| 42 |
{ |
| 43 |
printf ("CPU clock speed: %4.0f MHz\n", get_cpu_clock_speed ()); |
| 44 |
return 0; |
| 45 |
} |