[cfe-commits] [PATCH] Add __builtin_readcyclecounter

Howard Hinnant hhinnant at apple.com
Sun Aug 5 06:52:35 PDT 2012

On Aug 4, 2012, at 11:28 PM, Hal Finkel <hfinkel at anl.gov> wrote:

> Hello,
> Please review this patch which adds a __builtin_readcyclecounter()
> intrinsic. LLVM provides i64 @llvm.readcyclecounter(), but clang does
> not have a corresponding intrinsic.
> Thanks in advance,
> Hal

Just fyi for everyone, here is how to hook such a builtin up to <chrono>, making it very convenient to use, at least if you know at compile time the speed of the machine you're running on:

#include <chrono>

namespace x

struct clock
    typedef unsigned long long                 rep;
    typedef std::ratio<1, 2800000000>          period; // My machine is 2.8 GHz
    typedef std::chrono::duration<rep, period> duration;
    typedef std::chrono::time_point<clock>     time_point;
    static const bool is_steady =              true;

    static time_point now() noexcept
        return time_point(duration(__builtin_readcyclecounter()));

}  // x

Now you can say things like:

auto t0 = x::clock::now();
// do stuff
auto t1 = x::clock::now();
using namespace std::chrono;
std::cout << "That took " << (t1-t0).count() << " clock cycles ("
          << duration_cast<nanoseconds>(t1-t0).count() << " ns).\n";

That took 18 clock cycles (6 ns).


More information about the cfe-commits mailing list