<p>I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux).</p>

<p>I have implemented <code>QueryPerformanceCounter</code> by giving the uSeconds since the process start up:     </p>

<pre><code>BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount)
{
    gettimeofday(&amp;currentTimeVal, NULL);
    performanceCount-&gt;QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec);
    performanceCount-&gt;QuadPart *= (1000 * 1000);
    performanceCount-&gt;QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);

    return true;
}
</code></pre>

<p>This, coupled with <code>QueryPerformanceFrequency()</code> giving a constant 1000000 as the frequency, works well <b>on my machine</b>, giving me a 64-bit variable that contains <code>uSeconds</code> since the program's start-up.</p>

<p>So <em>is this portable?</em> I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.</p>

[{'answer_id': 93, 'author': 'CodingWithoutComments', 'author_id': 25, 'author_profile': 'https://Stackoverflow.com/users/25', 'pm_score': 2, 'selected': False, 'text': '<p>From my experience, and from what I\'ve read across the internet, the answer is "No," it is not guaranteed.  It depends on CPU speed, operating system, flavor of Linux, etc.</p>\n'}, {'answer_id': 98, 'author': 'Louis Brandy', 'author_id': 2089740, 'author_profile': 'https://Stackoverflow.com/users/2089740', 'pm_score': 7, 'selected': True, 'text': '<p>Maybe. But you have bigger problems. <code>gettimeofday()</code> can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a "normal" linux, though, I believe the resolution of <code>gettimeofday()</code> is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no.</p>\n\n<p>You should look into <code>clock_gettime(CLOCK_MONOTONIC)</code> for timing intervals. It suffers from several less issues due to things like multi-core systems and external clock settings.</p>\n\n<p>Also, look into the <code>clock_getres()</code> function.</p>\n'}, {'answer_id': 99, 'author': 'CodingWithoutComments', 'author_id': 25, 'author_profile': 'https://Stackoverflow.com/users/25', 'pm_score': 3, 'selected': False, 'text': '<blockquote>\n  <p>The actual resolution of gettimeofday() depends on the hardware architecture. Intel processors as well as SPARC machines offer high resolution timers that measure microseconds. Other hardware architectures fall back to the system’s timer, which is typically set to 100 Hz. In such cases, the time resolution will be less accurate. </p>\n</blockquote>\n\n<p>I obtained this answer from <a href="http://web.archive.org/web/20160711223333/http://www.informit.com/guides/content.aspx?g=cplusplus&amp;seqNum=272" rel="nofollow noreferrer">High Resolution Time Measurement and Timers, Part I</a></p>\n'}, {'answer_id': 367, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 5, 'selected': False, 'text': '<p><strong>High Resolution, Low Overhead Timing for Intel Processors</strong></p>\n\n<p>If you\'re on Intel hardware, here\'s how to read the CPU real-time instruction counter.  It will tell you the number of CPU cycles executed since the processor was booted.  This is probably the finest-grained counter you can get for performance measurement.</p>\n\n<p>Note that this is the number of CPU cycles.  On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds.  Converting this to a double is quite handy.</p>\n\n<p>When I run this on my box, I get</p>\n\n<pre><code>11867927879484732\n11867927879692217\nit took this long to call printf: 207485\n</code></pre>\n\n<p>Here\'s the <a href="http://cs.smu.ca/~jamuir/rdtscpm1.pdf" rel="noreferrer">Intel developer\'s guide</a> that  gives tons of detail.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdint.h&gt;\n\ninline uint64_t rdtsc() {\n    uint32_t lo, hi;\n    __asm__ __volatile__ (\n      "xorl %%eax, %%eax\\n"\n      "cpuid\\n"\n      "rdtsc\\n"\n      : "=a" (lo), "=d" (hi)\n      :\n      : "%ebx", "%ecx");\n    return (uint64_t)hi &lt;&lt; 32 | lo;\n}\n\nmain()\n{\n    unsigned long long x;\n    unsigned long long y;\n    x = rdtsc();\n    printf("%lld\\n",x);\n    y = rdtsc();\n    printf("%lld\\n",y);\n    printf("it took this long to call printf: %lld\\n",y-x);\n}\n</code></pre>\n'}, {'answer_id': 522, 'author': 'Joe Shaw', 'author_id': 156, 'author_profile': 'https://Stackoverflow.com/users/156', 'pm_score': 3, 'selected': False, 'text': "<blockquote>\n  <p>So it says microseconds explicitly, but says the resolution of the system clock is unspecified. I suppose resolution in this context means how the smallest amount it will ever be incremented?</p>\n</blockquote>\n\n<p>The data structure is defined as having microseconds as a unit of measurement, but that doesn't mean that the clock or operating system is actually capable of measuring that finely.</p>\n\n<p>Like other people have suggested, <code>gettimeofday()</code> is bad because setting the time can cause clock skew and throw off your calculation.  <code>clock_gettime(CLOCK_MONOTONIC)</code> is what you want, and <code>clock_getres()</code> will tell you the precision of your clock.</p>\n"}, {'answer_id': 931, 'author': 'Mark Harrison', 'author_id': 116, 'author_profile': 'https://Stackoverflow.com/users/116', 'pm_score': 4, 'selected': False, 'text': '<p>@Bernard:</p>\n\n<blockquote>\n  <p>I have to admit, most of your example went straight over my head. It does compile, and seems to work, though. Is this safe for SMP systems or SpeedStep?</p>\n</blockquote>\n\n<p>That\'s a good question... I think the code\'s ok.\nFrom a practical standpoint, we use it in my company every day,\nand we run on a pretty wide array of boxes, everything from 2-8 cores.\nOf course, YMMV, etc, but it seems to be a reliable and low-overhead\n(because it doesn\'t make a context switch into system-space) method\nof timing.</p>\n\n<p>Generally how it works is:</p>\n\n<ul>\n<li>declare the block of code to be assembler (and volatile, so the\noptimizer will leave it alone).</li>\n<li>execute the CPUID instruction.  In addition to getting some CPU information\n(which we don\'t do anything with) it synchronizes the CPU\'s execution buffer\nso that the timings aren\'t affected by out-of-order execution.</li>\n<li>execute the rdtsc (read timestamp) execution.  This fetches the number of\nmachine cycles executed since the processor was reset.  This is a 64-bit\nvalue, so with current CPU speeds it will wrap around every 194 years or so.\nInterestingly, in the original Pentium reference, they note it wraps around every\n5800 years or so.</li>\n<li>the last couple of lines store the values from the registers into\nthe variables hi and lo, and put that into the 64-bit return value.</li>\n</ul>\n\n<p>Specific notes:</p>\n\n<ul>\n<li><p>out-of-order execution can cause incorrect results, so we execute the\n"cpuid" instruction which in addition to giving you some information\nabout the cpu also synchronizes any out-of-order instruction execution.</p></li>\n<li><p>Most OS\'s synchronize the counters on the CPUs when they start, so\nthe answer is good to within a couple of nano-seconds.</p></li>\n<li><p>The hibernating comment is probably true, but in practice you\nprobably don\'t care about timings across hibernation boundaries.</p></li>\n<li><p>regarding speedstep: Newer Intel CPUs compensate for the speed\nchanges and returns an adjusted count.  I did a quick scan over\nsome of the boxes on our network and found only one box that\ndidn\'t have it: a Pentium 3 running some old database server.\n(these are linux boxes, so I checked with: grep constant_tsc /proc/cpuinfo)</p></li>\n<li><p>I\'m not sure about the AMD CPUs, we\'re primarily an Intel shop,\nalthough I know some of our low-level systems gurus did an\nAMD evaluation.</p></li>\n</ul>\n\n<p>Hope this satisfies your curiosity, it\'s an interesting and (IMHO)\nunder-studied area of programming.  You know when Jeff and Joel were\ntalking about whether or not a programmer should know C?  I was\nshouting at them, "hey forget that high-level C stuff... assembler\nis what you should learn if you want to know what the computer is\ndoing!"</p>\n'}, {'answer_id': 1290, 'author': 'Vincent Robert', 'author_id': 268, 'author_profile': 'https://Stackoverflow.com/users/268', 'pm_score': 4, 'selected': False, 'text': '<p>Wine is actually using gettimeofday() to implement QueryPerformanceCounter() and it is known to make many Windows games work on Linux and Mac.</p>\n\n<p>Starts <a href="http://source.winehq.org/source/dlls/kernel32/cpu.c#L312" rel="noreferrer">http://source.winehq.org/source/dlls/kernel32/cpu.c#L312</a></p>\n\n<p>leads to <a href="http://source.winehq.org/source/dlls/ntdll/time.c#L448" rel="noreferrer">http://source.winehq.org/source/dlls/ntdll/time.c#L448</a></p>\n'}, {'answer_id': 14807, 'author': 'Doug', 'author_id': 1618, 'author_profile': 'https://Stackoverflow.com/users/1618', 'pm_score': 2, 'selected': False, 'text': '<p>Reading the RDTSC is not reliable in SMP systems, since each CPU maintains their own counter and each counter is not guaranteed to by synchronized with respect to another CPU.</p>\n\n<p>I might suggest trying <strong><code>clock_gettime(CLOCK_REALTIME)</code></strong>. The posix manual indicates that this should be implemented on all compliant systems. It can provide a nanosecond count, but you probably will want to check <strong><code>clock_getres(CLOCK_REALTIME)</code></strong> on your system to see what the actual resolution is.</p>\n'}, {'answer_id': 14817, 'author': 'David Schlosnagle', 'author_id': 1750, 'author_profile': 'https://Stackoverflow.com/users/1750', 'pm_score': 4, 'selected': False, 'text': '<p>You may be interested in <a href="http://juliusdavies.ca/posix_clocks/clock_realtime_linux_faq.html" rel="noreferrer">Linux FAQ for <code>clock_gettime(CLOCK_REALTIME)</code></a></p>\n'}, {'answer_id': 11211298, 'author': 'bames53', 'author_id': 365496, 'author_profile': 'https://Stackoverflow.com/users/365496', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://stackoverflow.com/a/98/">This answer</a> mentions problems with the clock being adjusted. Both your problems guaranteeing tick units and the problems with the time being adjusted are solved in C++11 with the <code>&lt;chrono&gt;</code> library.</p>\n\n<p>The clock <code>std::chrono::steady_clock</code> is guaranteed not to be adjusted, and furthermore it will advance at a constant rate relative to real time, so technologies like SpeedStep must not affect it.</p>\n\n<p>You can get typesafe units by converting to one of the <code>std::chrono::duration</code> specializations, such as <code>std::chrono::microseconds</code>. With this type there\'s no ambiguity about the units used by the tick value. However, keep in mind that the clock doesn\'t necessarily have this resolution. You can convert a duration to attoseconds without actually having a clock that accurate.</p>\n'}]
['https://Stackoverflow.com/questions/88', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61/']