source: icGREP/icgrep-devel/icgrep/hrtime.h @ 5208

Last change on this file since 5208 was 4937, checked in by nmedfort, 3 years ago

Check in of misc changes prior to symbol table work.

File size: 1.5 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")) == nullptr)
19    return -1;
20
21  // ignore all lines until we reach MHz information
22  while (fgets(line, 1024, fp) != nullptr) {
23    if (strstr(line, search_str) != nullptr) {
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 != nullptr)
34    fclose(fp);
35  return mhz;
36}
37
38typedef uint64_t timestamp_t;
39
40// get the number of CPU cycles since startup using rdtsc instruction
41static inline timestamp_t read_cycle_counter() {
42#ifdef __GNUC__
43timestamp_t ts;
44#ifdef __x86_64__
45  unsigned int eax, edx;
46  asm volatile("rdtsc" : "=a" (eax), "=d" (edx));
47  ts = ((timestamp_t) eax) | (((timestamp_t) edx) << 32);
48#else
49  asm volatile("rdtsc\n" : "=A" (ts));
50#endif
51  return(ts);
52#endif
53#ifdef _MSC_VER
54  return __rdtsc();
55#endif
56}
57
58// get the elapsed time (in milliseconds) since startup
59inline double getElapsedTime() {
60  static double CPU_HZ = 0;
61  if (CPU_HZ == 0)
62    CPU_HZ = getMHZ() * 1000000;
63  return (read_cycle_counter() / CPU_HZ);
64}
65
66#endif // __HRTIME_H__
67
Note: See TracBrowser for help on using the repository browser.