快速计算在C程序中执行的指令数的方法 [英] Quick way to count number of instructions executed in a C program
问题描述
有没有一种简便的方法可以快速计算执行C程序时执行的指令数量(x86指令-每个指令的数量和数量)?
Is there an easy way to quickly count the number of instructions executed (x86 instructions - which and how many each) while executing a C program ?
我在 x86_64 GNU/Linux
机器上使用 gcc版本4.7.1(GCC)
.
推荐答案
Linux perf_event_open
系统调用,其中 config = PERF_COUNT_HW_INSTRUCTIONS
Linux perf_event_open
system call with config = PERF_COUNT_HW_INSTRUCTIONS
此Linux系统调用似乎是性能事件的跨体系结构包装,包括来自CPU的硬件性能计数器和来自内核的软件事件.
This Linux system call appears to be a cross architecture wrapper for performance events, including both hardware performance counters from the CPU and software events from the kernel.
这是从 man perf_event_open
页面改编的示例:
Here's an example adapted from the man perf_event_open
page:
perf_event_open.c
perf_event_open.c
#define _GNU_SOURCE
#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>
#include <sys/types.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_INSTRUCTIONS;
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("Used %lld instructions\n", count);
close(fd);
}
编译并运行:
g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o perf_event_open.out perf_event_open.c
./perf_event_open.out
输出:
Used 20016 instructions
因此,我们看到结果非常接近20000的预期值:10k *每个循环在 __ asm __
块( sub
, jne
).
So we see that the result is pretty close to the expected value of 20000: 10k * two instructions per loop in the __asm__
block (sub
, jne
).
如果我改变参数,甚至降低到 100
之类的低值:
If I vary the argument, even to low values such as 100
:
./perf_event_open.out 100
它给出:
Used 216 instructions
保持该常数+ 16条指令,因此精度似乎很高,在我们的小循环之后,这16条指令必须只是 ioctl
设置指令.
maintaining that constant + 16 instructions, so it seems that accuracy is pretty high, those 16 must be just the ioctl
setup instructions after our little loop.
现在您可能也对以下内容感兴趣:
Now you might also be interested in: