Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Here's a solution for GNU/Linux that uses the x86 CPU timestamp counter:</p> <ul> <li>Caveat: Only works on x86 and non-tickless kernels...</li> <li>Trivia: who can tell us what the timing returned is on a tickless kernel?</li> <li>Hint: it won't be real time</li> </ul> <p>rdtsc.c:</p> <pre><code>#include &lt;sys/time.h&gt; #include &lt;time.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; typedef unsigned long long int64; static __inline__ int64 getticks(void) { unsigned a, d; asm volatile("rdtsc" : "=a" (a), "=d" (d)); return (((int64)a) | (((int64)d) &lt;&lt; 32)); } int main(){ int64 tick,tick1; unsigned time=0,ut,mt; // ut is the divisor to give microseconds // mt gives milliseconds FILE *pf; int i,r,l,n=0; char s[100]; // time how long it takes to get the divisors, as a test tick = getticks(); // get the divisors - todo: for max performance this can // output a new binary or library with these values hardcoded // for the relevant CPU - a kind-of ludicrous notion considering // that this will only work on x86 compatible cpus anyways where // performance is the least of your issues... // ... curse of the assembly coder ;-) pf = fopen("/proc/cpuinfo","r"); do { r=fscanf(pf,"%s",&amp;s[0]); if (r&lt;0) { n=5; break; } else if (n==0) { if (strcmp("MHz",s)==0) n=1; } else if (n==1) { if (strcmp(":",s)==0) n=2; } else if (n==2) { n=3; }; } while (n&lt;3); fclose(pf); l=strlen(s); s[l-4]=s[l-3]; s[l-3]=s[l-2]; s[l-2]=s[l-1]; s[l-1]=(char)0; mt=atoi(s); s[l-4]=(char)0; ut=atoi(s); printf("%s Mhz - ut = %u, mt = %u // hardcode these for your a CPU-specific binary ;-)\n",s,ut,mt); tick1 = getticks(); time = (unsigned)((tick1-tick)/ut); printf("%u us\n",time); // time the duration of sleep(1) - plus overheads ;-) tick = getticks(); sleep(1); tick1 = getticks(); time = (unsigned)((tick1-tick)/mt); printf("%u ms\n",time); return 0; } </code></pre> <p>compile and run with</p> <blockquote> <p>$ gcc rdtsc.c -o rdtsc &amp;&amp; ./rdtsc</p> </blockquote> <p>It reads the correct divisor for your CPU from /proc/cpuinfo and shows how long it took to read that in microseconds, as well as how long it takes to execute sleep(1) in milliseconds.</p> <p>... Assuming the Mhz rating in /proc/cpuinfo always contains 3 decimal places :-o</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload