Line data Source code
1 : #include <stdio.h>
2 : #include <string.h>
3 : #include <errno.h>
4 : #include <stdlib.h>
5 : #include <ctype.h>
6 :
7 : #define PPC64
8 :
9 : unsigned long long tbr32(void);
10 : unsigned long long tbr64(void);
11 :
12 : static unsigned long long timebase_frequency = 2.061e9;
13 : static unsigned long long cpu_frequency;
14 :
15 : #if 1
16 0 : void init_timebase(void)
17 : {
18 : FILE* fp;
19 0 : char* file = "/proc/cpuinfo";
20 : char line[BUFSIZ];
21 : char* s;
22 : char* t;
23 : double f; /* for reading the CPU frequency. */
24 :
25 0 : errno = 0;
26 :
27 0 : fp = fopen(file, "r");
28 :
29 0 : if (fp == NULL) {
30 0 : fprintf(stderr, "cannot open \"%s\" for reading: ", file);
31 0 : perror(0);
32 0 : fprintf(stderr, "\n");
33 : } else {
34 0 : while (fgets(line, BUFSIZ, fp) != NULL) {
35 0 : if (strncmp(line, "clock", 5) == 0
36 0 : && (s = strchr(line, ':')) != NULL) {
37 :
38 0 : s += 1; /* skip ':' */
39 :
40 0 : while (!isdigit(*s) && *s != 0)
41 0 : s += 1;
42 :
43 0 : if (!isdigit(*s)) {
44 0 : fprintf(stderr, "expected a digit when reading %s line for clock\n",
45 : file);
46 0 : return;
47 : }
48 :
49 0 : errno = 0;
50 : #if 0
51 : f = 3.491;
52 : #else
53 0 : f = strtod(s, &t);
54 : #endif
55 0 : if (errno != 0) {
56 0 : fprintf(stderr, "could not read clock value from input: %s\n", s);
57 0 : f = 0;
58 : }
59 :
60 0 : if (strncmp(t, "MHz", 3) == 0)
61 0 : f *= 1e6;
62 0 : else if (strncmp(t, "GHz", 3) == 0)
63 0 : f *= 1e9;
64 : else
65 0 : fprintf(stderr, "warning: could not read CPU frequency unit from: %s\n", s);
66 : //fprintf(stderr, "init_timebase: CPU frequency: %1.1lf Hz\n", f);
67 0 : cpu_frequency = f;
68 :
69 0 : } else if (strncmp(line, "timebase", 8) == 0
70 0 : && (s = strchr(line, ':')) != NULL) {
71 :
72 0 : s += 1; /* skip ':' */
73 :
74 0 : while (!isdigit(*s) && *s != 0)
75 0 : s += 1;
76 :
77 0 : if (!isdigit(*s)) {
78 0 : fprintf(stderr, "expected a digit when reading %s line for timebase\n",
79 : file);
80 0 : return;
81 : }
82 :
83 0 : errno = 0;
84 0 : timebase_frequency = atoll(s);
85 0 : if (errno != 0) {
86 0 : fprintf(stderr, "could not read timebase value from input: %s\n", s);
87 0 : timebase_frequency = 0;
88 : }
89 : }
90 : }
91 :
92 0 : fclose(fp);
93 : }
94 : }
95 : #endif
96 :
97 0 : unsigned long long timebase()
98 : {
99 : #if defined PPC64
100 0 : return tbr64();
101 : #elif defined PPC32
102 : return tbr32();
103 : #else
104 : #error PPC32 or PPC64 must be defined
105 : #endif
106 : }
107 :
108 0 : double timebase_sec(void)
109 : {
110 0 : return timebase() / (double)timebase_frequency;
111 : }
112 :
113 0 : double timebase_cycles(unsigned long long timebase_count)
114 : {
115 0 : return timebase_count * (double)cpu_frequency / (double)timebase_frequency;
116 : }
|