<p>What are the common algorithms being used to measure the processor frequency?</p>

[{'answer_id': 65159, 'author': 'Todd Gamblin', 'author_id': 9122, 'author_profile': 'https://Stackoverflow.com/users/9122', 'pm_score': 0, 'selected': False, 'text': "<p>I'm not sure why you need assembly for this.  If you're on a machine that has the /proc filesystem, then running:</p>\n\n<pre><code>&gt; cat /proc/cpuinfo\n</code></pre>\n\n<p>might give you what you need.</p>\n"}, {'answer_id': 65178, 'author': 'DGentry', 'author_id': 4761, 'author_profile': 'https://Stackoverflow.com/users/4761', 'pm_score': 1, 'selected': False, 'text': '<p>That was the intention of things like <A HREF="http://en.wikipedia.org/wiki/BogoMips" rel="nofollow noreferrer">BogoMIPS</A>, but CPUs are a lot more complicated nowadays. Superscalar CPUs can issue multiple instructions per clock, making any measurement based on counting clock cycles to execute a block of instructions highly inaccurate.</p>\n\n<p>CPU frequencies are also variable based on offered load and/or temperature. The fact that the CPU is currently running at 800 MHz does not mean it will always be running at 800 MHz, it might throttle up or down as needed.</p>\n\n<p>If you really need to know the clock frequency, it should be passed in as a parameter. An EEPROM on the board would supply the base frequency, and if the clock can vary you\'d need to be able to read the CPUs power state registers (or make an OS call) to find out the frequency at that instant.</p>\n\n<p>With all that said, there may be other ways to accomplish what you\'re trying to do. For example if you want to make high-precision measurements of how long a particular codepath takes, the CPU likely has performance counters running at a fixed frequency which are a better measure of wall-clock time than reading a tick count register.</p>\n'}, {'answer_id': 65369, 'author': 'Nathan Fellman', 'author_id': 1084, 'author_profile': 'https://Stackoverflow.com/users/1084', 'pm_score': 4, 'selected': False, 'text': '<p>Intel CPUs after Core Duo support two Model-Specific registers called IA32_MPERF and IA32_APERF.<br>\nMPERF counts at the maximum frequency the CPU supports, while APERF counts at the actual current frequency.</p>\n\n<p>The actual frequency is given by:</p>\n\n<p><img src="https://chart.apis.google.com/chart?cht=tx&amp;chl=%5CLARGE%5C%21freq%20%3D%20%5Cfrac%7Bmax%20frequency%20%5Ccdot%20APERF%7D%7BMPERF%7D" alt="freq = max_frequency * APERF / MPERF"></p>\n\n<p>You can read them with this flow</p>\n\n<pre><code>; read MPERF\nmov ecx, 0xe7\nrdmsr\nmov mperf_var_lo, eax\nmov mperf_var_hi, edx\n\n; read APERF\nmov ecx, 0xe8\nrdmsr\nmov aperf_var_lo, eax\nmov aperf_var_hi, edx\n</code></pre>\n\n<p>but note that rdmsr is a privileged instruction and can run only in ring 0.</p>\n\n<p>I don\'t know if the OS provides an interface to read these, though their main usage is for power management, so it might not provide such an interface.</p>\n'}, {'answer_id': 118369, 'author': 'Tim Farley', 'author_id': 4425, 'author_profile': 'https://Stackoverflow.com/users/4425', 'pm_score': 3, 'selected': False, 'text': "<p>I'm gonna date myself with various details in this answer, but what the heck...</p>\n\n<p>I had to tackle this problem years ago on Windows-based PCs, so I was dealing with Intel x86 series processors like 486, Pentium and so on.  The standard algorithm in that situation was to do a long series of DIVide instructions, because those are typically the most CPU-bound single instructions in the Intel set.  So memory prefetch and other architectural issues do not materially affect the instruction execution time -- the prefetch queue is always full and the instruction itself does not touch any other memory.  </p>\n\n<p>You would time it using the highest resolution clock you could get access to in the environment you are running in.  (In my case I was running near boot time on a PC compatible, so I was directly programming the timer chips on the motherboard.  Not recommended in a real OS, usually there's some appropriate API to call these days).</p>\n\n<p>The main problem you have to deal with is different CPU types.  At that time there was Intel, AMD and some smaller vendors like Cyrix making x86 processors.  Each model had its own performance characteristics vis-a-vis that DIV instruction.  My assembly timing function would just return a number of clock cycles taken by a certain fixed number of DIV instructions done in a tight loop.</p>\n\n<p>So what I did was to gather some timings (raw return values from that function) from actual PCs running each processor model I wanted to time, and record those in a spreadsheet against the known processor speed and processor type.  I actually had a command-line tool that was just a thin shell around my timing function, and I would take a disk into computer stores and get the timings off of display models!  (I worked for a very small company at the time).</p>\n\n<p>Using those raw timings, I could plot a theoretical graph of what timings I should get for any known speed of that particular CPU.</p>\n\n<p>Here was the trick:  I always hated when you would run a utility and it would announce that your CPU was 99.8 Mhz or whatever.  Clearly it was 100 Mhz and there was just a small round-off error in the measurement.  In my spreadsheet I recorded the actual speeds that were sold by each processor vendor.  Then I would use the plot of actual timings to estimate projected timings for any known speed.  But I would build a table of points along the line where the timings should round to the next speed.</p>\n\n<p>In other words, if 100 ticks to do all that repeating dividing meant 500 Mhz, and 200 ticks meant 250 Mhz, then I would build a table that said that anything below 150 was 500 Mhz, and anything above that was 250 Mhz.  (Assuming those were the only two speeds available from that chip vendor).  It was nice because even if some odd piece of software on the PC was throwing off my timings, the end result would often still be dead on.</p>\n\n<p>Of course now, in these days of overclocking, dynamic clock speeds for power management, and other such trickery, such a scheme would be much less practical.  At the very least you'd need to do something to make sure the CPU was in its highest dynamically chosen speed first before running your timing function.</p>\n\n<p>OK, I'll go back to shooing kids off my lawn now.</p>\n"}, {'answer_id': 418923, 'author': 'Calyth', 'author_id': 45144, 'author_profile': 'https://Stackoverflow.com/users/45144', 'pm_score': 0, 'selected': False, 'text': '<p>A quick google on <a href="http://www.amd.com/us-en/Processors/ProductInformation/0,,30_118_6291_965%5E871%5E2364,00.html" rel="nofollow noreferrer">AMD</a> and <a href="http://www.intel.com/assets/pdf/appnote/241618.pdf" rel="nofollow noreferrer">Intel</a> shows that CPUID should give you access to the CPU`s max frequency.</p>\n'}, {'answer_id': 689125, 'author': 'Sam Liao', 'author_id': 75501, 'author_profile': 'https://Stackoverflow.com/users/75501', 'pm_score': 1, 'selected': False, 'text': '<p>"lmbench" provides a cpu frequency algorithm portable for different architecture. </p>\n\n<p>It runs some different loops and  the processor\'s clock speed is the greatest common divisor of the execution frequencies of the various loops.</p>\n\n<p>this method should always work when we are able to get loops with cycle counts that are relatively prime.                        </p>\n\n<p><a href="http://www.bitmover.com/lmbench/" rel="nofollow noreferrer">http://www.bitmover.com/lmbench/</a></p>\n'}, {'answer_id': 1048120, 'author': 'matja', 'author_id': 115567, 'author_profile': 'https://Stackoverflow.com/users/115567', 'pm_score': 2, 'selected': False, 'text': '<p>One way on x86 Intel CPU\'s since Pentium would be to use two samplings of the RDTSC instruction with a delay loop of known wall time, eg: </p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;unistd.h&gt;\n\nuint64_t rdtsc(void) {\n    uint64_t result;\n    __asm__ __volatile__ ("rdtsc" : "=A" (result));\n    return result;\n}\n\nint main(void) {\n    uint64_t ts0, ts1;    \n    ts0 = rdtsc();\n    sleep(1);\n    ts1 = rdtsc();    \n    printf("clock frequency = %llu\\n", ts1 - ts0);\n    return 0;\n}\n</code></pre>\n\n<p>(on 32-bit platforms with GCC)</p>\n\n<p>RDTSC is available in ring 3 if the TSC flag in CR4 is set, which is common but not guaranteed.  One shortcoming of this method is that it is vulnerable to frequency scaling changes affecting the result if they happen inside the delay.  To mitigate that you could execute code that keeps the CPU busy and constantly poll the system time to see if your delay period has expired, to keep the CPU in the highest frequency state available.</p>\n'}, {'answer_id': 6953905, 'author': 'Olof Forshell', 'author_id': 501673, 'author_profile': 'https://Stackoverflow.com/users/501673', 'pm_score': 2, 'selected': False, 'text': "<p>I use the following (pseudo)algorithm:</p>\n\n<pre><code>basetime=time();    /* time returns seconds */\n\nwhile (time()==basetime);\nstclk=rdtsc();    /* rdtsc is an assembly instruction */\n\nbasetime=time();\nwhile (time()==basetime\nendclk=rdtsc();\n\nnclks=encdclk-stclk;\n</code></pre>\n\n<p>At this point you might assume that you've determined the clock frequency but even though it appears correct it can be improved.</p>\n\n<p>All PCs contain a PIT (Programmable Interval Timer) device which contains counters which are (used to be) used for serial ports and the system clock. It was fed with a frequency of 1193182 Hz. The system clock counter was set to the highest countdown value (65536) resulting in a system clock tick frequency of 1193182/65536 => 18.2065 Hz or once every 54.925 milliseconds.</p>\n\n<p>The number of ticks necessary for the clock to increment to the next second will therefore depend. Usually 18 ticks are required and sometimes 19. This can be handled by performing the algorithm (above) twice and storing the results. The two results will either be equivalent to two 18 tick sequences or one 18 and one 19. Two 19s in a row won't occur. So by taking the smaller of the two results you will have an 18 tick second. Adjust this result by multiplying with 18.2065 and dividing by 18.0 or, using integer arithmetic, multiply by 182065, add 90000 and divide by 180000. 90000 is one half of 180000 and is there for rounding. If you choose the calculation with integer route make sure you are using 64-bit multiplication and division.</p>\n\n<p>You will now have a CPU clock speed x in Hz which can be converted to kHz ((x+500)/1000) or MHz ((x+5000000)/1000000). The 500 and 500000 are one half of 1000 and 1000000 respectively and are there for rounding. To calculate MHz do not go via the kHz value because rounding issues may arise. Use the Hz value and the second algorithm.</p>\n"}, {'answer_id': 33160613, 'author': 'Patrick', 'author_id': 4919054, 'author_profile': 'https://Stackoverflow.com/users/4919054', 'pm_score': 1, 'selected': False, 'text': '<p>One option is to sense the CPU frequency, by running code with known instructions per loop</p>\n\n<p>This functionality is contained in 7zip, since about v9.20 I think.</p>\n\n<pre><code>&gt; 7z b\n7-Zip 9.38 beta  Copyright (c) 1999-2014 Igor Pavlov  2015-01-03\n\nCPU Freq:  4266  4000  4266  4000  2723  4129  3261  3644  3362\n</code></pre>\n\n<p>The final number is meant to be correct (and on my PC and many others, I have found it to be quite correct - the test runs very quick so turbo may not kick in, and servers set in Balanced/Power Save modes most likely give readings of around 1ghz)</p>\n\n<p>The source code is at <a href="https://github.com/jljusten/LZMA-SDK/blob/master/CPP/7zip/UI/Common/Bench.cpp" rel="nofollow">GitHub</a> (Official source is a download from 7-zip.org)</p>\n\n<p>With the most significant portion being:</p>\n\n<pre><code>#define YY1 sum += val; sum ^= val;\n#define YY3 YY1 YY1 YY1 YY1\n#define YY5 YY3 YY3 YY3 YY3\n#define YY7 YY5 YY5 YY5 YY5\nstatic const UInt32 kNumFreqCommands = 128;\n\nEXTERN_C_BEGIN\n\nstatic UInt32 CountCpuFreq(UInt32 sum, UInt32 num, UInt32 val)\n{\n  for (UInt32 i = 0; i &lt; num; i++)\n  {\n    YY7\n  }\n  return sum;\n}\n\nEXTERN_C_END\n</code></pre>\n'}, {'answer_id': 61429118, 'author': 'maxschlepzig', 'author_id': 427158, 'author_profile': 'https://Stackoverflow.com/users/427158', 'pm_score': 1, 'selected': False, 'text': '<p>On Intel CPUs, a common method to get the current (average) CPU frequency is to calculate it from a few CPU counters:</p>\n\n<pre><code>CPU_freq = tsc_freq * (aperf_t1 - aperf_t0) / (mperf_t1 - mperf_t0)\n</code></pre>\n\n<p>The <a href="https://en.wikipedia.org/wiki/Time_Stamp_Counter" rel="nofollow noreferrer">TSC</a> (Time Stamp Counter) can be read from userspace with dedicated x86 instructions, but its frequency has to be determined by calibration against a clock. The best approach is to <a href="https://stackoverflow.com/a/57835630/427158">get the TSC frequency from the kernel</a> (which already has done the calibration).</p>\n\n<p>The aperf and mperf counters are model specific registers <a href="https://en.wikipedia.org/wiki/Model-specific_register" rel="nofollow noreferrer">MSRs</a> that require root privileges for access. Again, there are dedicated x86 instructions for accessing the MSRs.</p>\n\n<p>Since the mperf counter rate is directly proportional to the TSC rate and the aperf rate is directly proportional to the CPU frequency you get the CPU frequency with the above equation.</p>\n\n<p>Of course, if the CPU frequency changes in your <code>t0 - t1</code> time delta (e.g. due due frequency scaling) you get the average CPU frequency with this method.</p>\n\n<p>I wrote a small utility <a href="https://github.com/gsauthof/utility/blob/master/cpufreq.py" rel="nofollow noreferrer">cpufreq</a> which can be used to test this method.</p>\n\n<p>See also:</p>\n\n<ul>\n<li><a href="https://lore.kernel.org/lkml/52f711be59539723358bea1aa3c368910a68b46d.1459485198.git.len.brown@intel.com/" rel="nofollow noreferrer">[PATCH] x86: Calculate MHz using APERF/MPERF for cpuinfo and scaling_cur_freq. 2016-04-01, LKML</a></li>\n<li><a href="https://lwn.net/Articles/816388/" rel="nofollow noreferrer">Frequency-invariant utilization tracking for x86. 2020-04-02, LWN.net</a></li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/65095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']