| 1 | #include <time.h>
|
|---|
| 2 | #include <stdint.h>
|
|---|
| 3 | #include <stdio.h>
|
|---|
| 4 | #include <stdlib.h>
|
|---|
| 5 | #include <unistd.h>
|
|---|
| 6 |
|
|---|
| 7 | uint64_t clk_mono() {
|
|---|
| 8 | struct timespec ts;
|
|---|
| 9 | clock_gettime(CLOCK_MONOTONIC, &ts);
|
|---|
| 10 | return ts.tv_sec * 1000000000L + ts.tv_nsec;
|
|---|
| 11 | }
|
|---|
| 12 |
|
|---|
| 13 | static inline uint64_t RDTSC() {
|
|---|
| 14 | unsigned hi, lo;
|
|---|
| 15 | __asm__ volatile("rdtsc"
|
|---|
| 16 | : "=a"(lo), "=d"(hi)
|
|---|
| 17 | : "a"(0)
|
|---|
| 18 | : "%ebx", "%ecx");
|
|---|
| 19 | return ((uint64_t)hi << 32) | lo;
|
|---|
| 20 | }
|
|---|
| 21 |
|
|---|
| 22 | #define NS_PER_S 1000000000UL
|
|---|
| 23 |
|
|---|
| 24 | void clk_test(unsigned sleep_ms) {
|
|---|
| 25 | uint64_t mono, mono0, last_mono, tsc;
|
|---|
| 26 | mono0 = last_mono = clk_mono();
|
|---|
| 27 | printf("# Monotonic_clock TSC\n");
|
|---|
| 28 | while (last_mono - mono0 < 60 * NS_PER_S) {
|
|---|
| 29 | usleep(1000 * sleep_ms);
|
|---|
| 30 | tsc = RDTSC();
|
|---|
| 31 | mono = clk_mono();
|
|---|
| 32 | if (mono - last_mono >= NS_PER_S / 2)
|
|---|
| 33 | {
|
|---|
| 34 | printf("%lu %lu\n", mono, tsc);
|
|---|
| 35 | last_mono = mono;
|
|---|
| 36 | }
|
|---|
| 37 | }
|
|---|
| 38 | }
|
|---|
| 39 |
|
|---|
| 40 | int main() {
|
|---|
| 41 | clk_test(0);
|
|---|
| 42 | printf("\n\n");
|
|---|
| 43 | clk_test(1);
|
|---|
| 44 | printf("\n\n");
|
|---|
| 45 | clk_test(10);
|
|---|
| 46 | printf("\n\n");
|
|---|
| 47 | clk_test(100);
|
|---|
| 48 | return 0;
|
|---|
| 49 | }
|
|---|