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

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

icgrep-0.8 distribution

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