Home > libalgo > タイマー

タイマー

概要

時間を測る.measure_ticks_per_second で出てきた値をハードコード.

実装

#include <unistd.h>

struct timer {
    int64_t start_tick_count;

    timer() { reset(); }

    void reset() { start_tick_count = get_tick_count(); }

    double get_ms() {
        int64_t diff = get_tick_count() - start_tick_count;
        return diff / TICKS_PER_SECOND;
    }

#if defined(_MSC_VER)
    static const int64_t TICKS_PER_SECOND = CLOCKS_PER_SEC;
#elseif defined(TOP_CODER)
    static const int64_t TICKS_PER_SECOND = 2500000000;
#else
    static const int64_t TICKS_PER_SECOND = 3400000000;
#endif

    int64_t get_tick_count() {
#ifdef _MSC_VER
        return clock();
#else
        uint32_t low, high;
        __asm__ volatile("rdtsc" : "=a"(low), "=d"(high));
        return ((int64_t)low) | ((int64_t)high << 32);
#endif
    }

    void measure_ticks_per_second() {
        int64_t start_t = get_tick_count();
        clock_t start_c = clock();
        while ((double)(clock() - start_c) / CLOCKS_PER_SEC < 10.0)
            ;
        std::cout << (get_tick_count() - start_t) / 10 << std::endl;
    }
};