答案 0 :(得分:6)
请clock_gettime()
标记为CLOCK_MONOTONIC_RAW
,clock_getres()
。
以下是如何使用它的示例:
答案 1 :(得分:2)
现在已经提供内核一段时间的perf
工具可能满足您的需求。它有一个s *负载的选项,所以仔细研究;)
答案 2 :(得分:0)
Linux perf_event_open
系统调用
此系统调用以不可知的方式公开了几个性能计数器。
man perf_event_open
记录了可用的计数器,其中包括您期望的所有最基本的内容:
config = PERF_COUNT_HW_CPU_CYCLES
)type = PERF_TYPE_HW_CACHE
)config = PERF_COUNT_HW_BRANCH_MISSES
)PERF_COUNT_SW_PAGE_FAULTS
)和上下文切换(PERF_COUNT_SW_CONTEXT_SWITCHES
)我在How to get the CPU cycle count in x86_64 from C++?
处给出了一个周期计数perf_event_open.c
#include <asm/unistd.h>
#include <linux/perf_event.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <inttypes.h>
static long
perf_event_open(struct perf_event_attr *hw_event, pid_t pid,
int cpu, int group_fd, unsigned long flags)
{
int ret;
ret = syscall(__NR_perf_event_open, hw_event, pid, cpu,
group_fd, flags);
return ret;
}
int
main(int argc, char **argv)
{
struct perf_event_attr pe;
long long count;
int fd;
uint64_t n;
if (argc > 1) {
n = strtoll(argv[1], NULL, 0);
} else {
n = 10000;
}
memset(&pe, 0, sizeof(struct perf_event_attr));
pe.type = PERF_TYPE_HARDWARE;
pe.size = sizeof(struct perf_event_attr);
pe.config = PERF_COUNT_HW_CPU_CYCLES;
pe.disabled = 1;
pe.exclude_kernel = 1;
// Don't count hypervisor events.
pe.exclude_hv = 1;
fd = perf_event_open(&pe, 0, -1, -1, 0);
if (fd == -1) {
fprintf(stderr, "Error opening leader %llx\n", pe.config);
exit(EXIT_FAILURE);
}
ioctl(fd, PERF_EVENT_IOC_RESET, 0);
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
/* Loop n times, should be good enough for -O0. */
__asm__ (
"1:;\n"
"sub $1, %[n];\n"
"jne 1b;\n"
: [n] "+r" (n)
:
:
);
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(long long));
printf("%lld\n", count);
close(fd);
}