Created
October 12, 2022 05:35
-
-
Save ShawSumma/8c39211e45b2904e315b6dcb69aed07f to your computer and use it in GitHub Desktop.
It's time to stop!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <asm/unistd.h> | |
#include <inttypes.h> | |
#include <linux/perf_event.h> | |
#include <stdio.h> | |
#include <sys/mman.h> | |
#include <unistd.h> | |
#include <stdint.h> | |
static uint64_t mul_u64_u32_shr(uint64_t cyc, uint32_t mult, uint32_t shift) { | |
__uint128_t x = cyc; | |
x *= mult; | |
x >>= shift; | |
return x; | |
} | |
static long perf_event_open(struct perf_event_attr *hw_event, pid_t pid, | |
int cpu, int group_fd, unsigned long flags) { | |
return syscall(__NR_perf_event_open, hw_event, pid, cpu, group_fd, flags); | |
} | |
static double get_rdtsc_ms() { | |
struct perf_event_attr pe = { | |
.type = PERF_TYPE_HARDWARE, | |
.size = sizeof(struct perf_event_attr), | |
.config = PERF_COUNT_HW_INSTRUCTIONS, | |
.disabled = 1, | |
.exclude_kernel = 1, | |
.exclude_hv = 1 | |
}; | |
int fd = perf_event_open(&pe, 0, -1, -1, 0); | |
if (fd == -1) { | |
perror("perf_event_open failed"); | |
return 1; | |
} | |
void *addr = mmap(NULL, 4*1024, PROT_READ, MAP_SHARED, fd, 0); | |
if (!addr) { | |
perror("mmap failed"); | |
return 1; | |
} | |
struct perf_event_mmap_page *pc = addr; | |
if (pc->cap_user_time != 1) { | |
fprintf(stderr, "Perf system doesn't support user time\n"); | |
return 1; | |
} | |
double nanos = (double)mul_u64_u32_shr(1000000, pc->time_mult, pc->time_shift); | |
return nanos / 1000000000; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment