Linux替代Windows高分辨率性能计数器API

时间:2011-12-15 15:05:49

标签: linux performancecounter

我正在寻找Windows高分辨率性能计数器API的Linux替代品,特别是以下API函数:

感谢。

3 个答案:

答案 0 :(得分:6)

clock_gettime()标记为CLOCK_MONOTONIC_RAWclock_getres()

以下是如何使用它的示例:

答案 1 :(得分:2)

现在已经提供内核一段时间的perf工具可能满足您的需求。它有一个s *负载的选项,所以仔细研究;)

编辑:忘了,我以为你在谈论CPU性能计数器。

答案 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);
}