如果我有一个函数foo,我想描述它的“用户”时间(删除内核或其他进程时间),我如何用代码(C/C++)来度量它?
我知道以下职能:
Windows
Linux
还有其他方法吗?每一个都提供了一个不同的时间‘观点’,而非真正提供准确的结果。
发布于 2013-04-04 11:27:28
在类似Unix的系统上,getrusage是您所要寻找的。特别是使用RUSAGE_SELF选项。用户时间将在ru_utime字段中的struct rusage中。ru_stime计算系统时间。
发布于 2013-04-17 16:08:36
在Linux上最好的方法如下:(从Linux内核perf_event_open手册页面中提取和修改)
代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/ioctl.h>
#include <linux/perf_event.h>
#include <asm/unistd.h>
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;
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;
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);
printf("Measuring instruction count for this printf\n");
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
read(fd, &count, sizeof(long long));
printf("Used %lld instructions\n", count);
close(fd);
}https://stackoverflow.com/questions/15809598
复制相似问题