rdtsc.c 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. /*
  2. * Copyright 2008 Veselin Georgiev,
  3. * anrieffNOSPAM @ mgail_DOT.com (convert to gmail)
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions
  7. * are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * 2. Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  16. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  17. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  18. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  19. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  20. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  21. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  22. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  23. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  24. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include "libcpuid.h"
  29. #include "libcpuid_util.h"
  30. #include "asm-bits.h"
  31. #include "rdtsc.h"
  32. #ifdef _WIN32
  33. #include <windows.h>
  34. void sys_precise_clock(uint64_t *result)
  35. {
  36. double c, f;
  37. LARGE_INTEGER freq, counter;
  38. QueryPerformanceCounter(&counter);
  39. QueryPerformanceFrequency(&freq);
  40. c = (double) counter.QuadPart;
  41. f = (double) freq.QuadPart;
  42. *result = (uint64_t) ( c * 1000000.0 / f );
  43. }
  44. #else
  45. /* assuming Linux, Mac OS or other POSIX */
  46. #include <sys/time.h>
  47. void sys_precise_clock(uint64_t *result)
  48. {
  49. struct timeval tv;
  50. gettimeofday(&tv, NULL);
  51. *result = (uint64_t) tv.tv_sec * (uint64_t) 1000000 +
  52. (uint64_t) tv.tv_usec;
  53. }
  54. #endif /* _WIN32 */
  55. /* out = a - b */
  56. static void mark_t_subtract(struct cpu_mark_t* a, struct cpu_mark_t* b, struct cpu_mark_t *out)
  57. {
  58. out->tsc = a->tsc - b->tsc;
  59. out->sys_clock = a->sys_clock - b->sys_clock;
  60. }
  61. void cpu_tsc_mark(struct cpu_mark_t* mark)
  62. {
  63. cpu_rdtsc(&mark->tsc);
  64. sys_precise_clock(&mark->sys_clock);
  65. }
  66. void cpu_tsc_unmark(struct cpu_mark_t* mark)
  67. {
  68. struct cpu_mark_t temp;
  69. cpu_tsc_mark(&temp);
  70. mark_t_subtract(&temp, mark, mark);
  71. }
  72. int cpu_clock_by_mark(struct cpu_mark_t* mark)
  73. {
  74. uint64_t result;
  75. /* Check if some subtraction resulted in a negative number: */
  76. if ((mark->tsc >> 63) != 0 || (mark->sys_clock >> 63) != 0) return -1;
  77. /* Divide-by-zero check: */
  78. if (mark->sys_clock == 0) return -1;
  79. /* Check if the result fits in 32bits */
  80. result = mark->tsc / mark->sys_clock;
  81. if (result > (uint64_t) 0x7fffffff) return -1;
  82. return (int) result;
  83. }
  84. #ifdef _WIN32
  85. int cpu_clock_by_os(void)
  86. {
  87. HKEY key;
  88. DWORD result;
  89. DWORD size = 4;
  90. if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), 0, KEY_READ, &key) != ERROR_SUCCESS)
  91. return -1;
  92. if (RegQueryValueEx(key, TEXT("~MHz"), NULL, NULL, (LPBYTE) &result, (LPDWORD) &size) != ERROR_SUCCESS) {
  93. RegCloseKey(key);
  94. return -1;
  95. }
  96. RegCloseKey(key);
  97. return (int)result;
  98. }
  99. #else
  100. #ifdef __APPLE__
  101. #include <sys/types.h>
  102. #include <sys/sysctl.h>
  103. /* Assuming Mac OS X with hw.cpufrequency sysctl */
  104. int cpu_clock_by_os(void)
  105. {
  106. long long result = -1;
  107. size_t size = sizeof(result);
  108. if (sysctlbyname("hw.cpufrequency", &result, &size, NULL, 0))
  109. return -1;
  110. return (int) (result / (long long) 1000000);
  111. }
  112. #else
  113. /* Assuming Linux with /proc/cpuinfo */
  114. int cpu_clock_by_os(void)
  115. {
  116. FILE *f;
  117. char line[1024], *s;
  118. int result;
  119. f = fopen("/proc/cpuinfo", "rt");
  120. if (!f) return -1;
  121. while (fgets(line, sizeof(line), f)) {
  122. if (!strncmp(line, "cpu MHz", 7)) {
  123. s = strchr(line, ':');
  124. if (s && 1 == sscanf(s, ":%d.", &result)) {
  125. fclose(f);
  126. return result;
  127. }
  128. }
  129. }
  130. fclose(f);
  131. return -1;
  132. }
  133. #endif /* __APPLE__ */
  134. #endif /* _WIN32 */
  135. /* Emulate doing useful CPU intensive work */
  136. static int busy_loop(int amount)
  137. {
  138. int i, j, k, s = 0;
  139. static volatile int data[42] = {32, 12, -1, 5, 23, 0 };
  140. for (i = 0; i < amount; i++)
  141. for (j = 0; j < 65536; j++)
  142. for (k = 0; k < 42; k++)
  143. s += data[k];
  144. return s;
  145. }
  146. int busy_loop_delay(int milliseconds)
  147. {
  148. int cycles = 0, r = 0, first = 1;
  149. uint64_t a, b, c;
  150. sys_precise_clock(&a);
  151. while (1) {
  152. sys_precise_clock(&c);
  153. if ((c - a) / 1000 > milliseconds) return r;
  154. r += busy_loop(cycles);
  155. if (first) {
  156. first = 0;
  157. } else {
  158. if (c - b < 1000) cycles *= 2;
  159. if (c - b > 10000) cycles /= 2;
  160. }
  161. b = c;
  162. }
  163. }
  164. int cpu_clock_measure(int millis, int quad_check)
  165. {
  166. struct cpu_mark_t begin[4], end[4], temp, temp2;
  167. int results[4], cycles, n, k, i, j, bi, bj, mdiff, diff, _zero = 0;
  168. uint64_t tl;
  169. if (millis < 1) return -1;
  170. tl = millis * (uint64_t) 1000;
  171. if (quad_check)
  172. tl /= 4;
  173. n = quad_check ? 4 : 1;
  174. cycles = 1;
  175. for (k = 0; k < n; k++) {
  176. cpu_tsc_mark(&begin[k]);
  177. end[k] = begin[k];
  178. do {
  179. /* Run busy loop, and fool the compiler that we USE the garbishy
  180. value it calculates */
  181. _zero |= (1 & busy_loop(cycles));
  182. cpu_tsc_mark(&temp);
  183. mark_t_subtract(&temp, &end[k], &temp2);
  184. /* If busy loop is too short, increase it */
  185. if (temp2.sys_clock < tl / 8)
  186. cycles *= 2;
  187. end[k] = temp;
  188. } while (end[k].sys_clock - begin[k].sys_clock < tl);
  189. mark_t_subtract(&end[k], &begin[k], &temp);
  190. results[k] = cpu_clock_by_mark(&temp);
  191. }
  192. if (n == 1) return results[0];
  193. mdiff = 0x7fffffff;
  194. bi = bj = -1;
  195. for (i = 0; i < 4; i++) {
  196. for (j = i + 1; j < 4; j++) {
  197. diff = results[i] - results[j];
  198. if (diff < 0) diff = -diff;
  199. if (diff < mdiff) {
  200. mdiff = diff;
  201. bi = i;
  202. bj = j;
  203. }
  204. }
  205. }
  206. if (results[bi] == -1) return -1;
  207. return (results[bi] + results[bj] + _zero) / 2;
  208. }
  209. int cpu_clock_by_ic(int millis, int runs)
  210. {
  211. int max_value = 0, cur_value, i, ri, cycles_inner, cycles_outer, c;
  212. struct cpu_id_t* id;
  213. uint64_t t0, t1, tl, hz;
  214. int multiplier_numerator = 1, multiplier_denom = 1;
  215. if (millis <= 0 || runs <= 0) return -2;
  216. id = get_cached_cpuid();
  217. // if there aren't SSE instructions - we can't run the test at all
  218. if (!id || !id->flags[CPU_FEATURE_SSE]) return -1;
  219. //
  220. if (id->sse_size < 128) {
  221. debugf(1, "SSE execution path is 64-bit\n");
  222. // on a CPU with half SSE unit length, SSE instructions execute at 0.5 IPC;
  223. // the resulting value must be multiplied by 2:
  224. multiplier_numerator = 2;
  225. } else {
  226. debugf(1, "SSE execution path is 128-bit\n");
  227. }
  228. //
  229. // on a Bulldozer or later CPU, SSE instructions execute at 1.4 IPC, handle that as well:
  230. if (id->vendor == VENDOR_AMD && id->ext_family >= 21) {
  231. debugf(1, "cpu_clock_by_ic: Bulldozer (or later) detected, dividing result by 1.4\n");
  232. multiplier_numerator = 5;
  233. multiplier_denom = 7; // multiply by 5/7, to divide by 1.4
  234. }
  235. //
  236. tl = millis * 125; // (*1000 / 8)
  237. cycles_inner = 128;
  238. cycles_outer = 1;
  239. do {
  240. if (cycles_inner < 1000000000) cycles_inner *= 2;
  241. else cycles_outer *= 2;
  242. sys_precise_clock(&t0);
  243. for (i = 0; i < cycles_outer; i++)
  244. busy_sse_loop(cycles_inner);
  245. sys_precise_clock(&t1);
  246. } while (t1 - t0 < tl);
  247. debugf(2, "inner: %d, outer: %d\n", cycles_inner, cycles_outer);
  248. for (ri = 0; ri < runs; ri++) {
  249. sys_precise_clock(&t0);
  250. c = 0;
  251. do {
  252. c++;
  253. for (i = 0; i < cycles_outer; i++)
  254. busy_sse_loop(cycles_inner);
  255. sys_precise_clock(&t1);
  256. } while (t1 - t0 < tl * (uint64_t) 8);
  257. // cpu_Hz = cycles_inner * cycles_outer * 256 / (t1 - t0) * 1000000
  258. debugf(2, "c = %d, td = %d\n", c, (int) (t1 - t0));
  259. hz = ((uint64_t) cycles_inner * (uint64_t) 256 + 12) *
  260. (uint64_t) cycles_outer * (uint64_t) multiplier_numerator * (uint64_t) c * (uint64_t) 1000000
  261. / ((t1 - t0) * (uint64_t) multiplier_denom);
  262. cur_value = (int) (hz / 1000000);
  263. if (cur_value > max_value) max_value = cur_value;
  264. }
  265. return max_value;
  266. }
  267. int cpu_clock(void)
  268. {
  269. int result;
  270. result = cpu_clock_by_os();
  271. if (result <= 0)
  272. result = cpu_clock_measure(200, 1);
  273. return result;
  274. }