source: icGREP/icgrep-0.8/icgrep/hrtime.h @ 3851

Last change on this file since 3851 was 3851, checked in by cameron, 5 years ago

Open Source License notices

File size: 1.3 KB
Line 
1#ifndef __HRTIME_H__
2#define __HRTIME_H__
3
4//Downloaded from code.Google.com
5
6#include <stdio.h>
7#include <string.h>
8#include <assert.h>
9
10// get the number of CPU cycles per microsecond from Linux /proc filesystem
11// return < 0 on error
12inline double getMHZ(void) {
13  double mhz = -1;
14  char line[1024], *s, search_str[] = "cpu MHz";
15  FILE* fp;
16
17  // open proc/cpuinfo
18  if ((fp = fopen("/proc/cpuinfo", "r")) == NULL)
19    return -1;
20
21  // ignore all lines until we reach MHz information
22  while (fgets(line, 1024, fp) != NULL) {
23    if (strstr(line, search_str) != NULL) {
24      // ignore all characters in line up to :
25      for (s = line; *s && (*s != ':'); ++s)
26        ;
27      // get MHz number
28      if (*s && (sscanf(s+1, "%lf", &mhz) == 1))
29        break;
30    }
31  }
32
33  if (fp != NULL)
34    fclose(fp);
35  return mhz;
36}
37
38// get the number of CPU cycles since startup using rdtsc instruction
39inline unsigned long long get_hrcycles() {
40  unsigned int tmp[2];
41  asm ("rdtsc" : "=a" (tmp[1]), "=d" (tmp[0]));
42  return (((unsigned long long)tmp[0] << 32 | tmp[1]));
43}
44
45// get the elapsed time (in milliseconds) since startup
46inline double getElapsedTime() {
47  static double CPU_HZ = 0;
48  if (CPU_HZ == 0)
49    CPU_HZ = getMHZ() * 1000000;
50  return (get_hrcycles() / CPU_HZ);
51}
52
53#endif // __HRTIME_H__
54
Note: See TracBrowser for help on using the repository browser.