我想测量从启动进程到使用C SIGINT
函数发送times
信号之间经过的CPU和用户时间。
但是,在印刷中,我只得到0
。看不到问题。
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/times.h>
#include <signal.h>
struct tms time_start;
struct tms time_end;
clock_t start;
clock_t end;
void handle() {
times(&time_end);
end = time_end.tms_stime;
}
int main(int argc, char *argv[]) {
signal(SIGINT, handle);
times(&time_start);
start = time_start.tms_utime;
pause();
printf("end: %ld, start: %ld\n", (long) end, (long) start);
return 0;
}
这是我得到的输出:
k@sc:dir$ ./my_time
^Cend: 0, start: 0
答案 0 :(得分:0)
在印刷品上我只能得到0。看不到问题。
tms_stime
是代表进程在内核中花费的CPU时间。 pause()
没有执行任何操作,因此它不占用CPU时间,signal
和times
并不是计算要求很高的函数-您的程序没有执行任何操作。做一些I / O操作,使该内核正常工作以查看时间上的某些变化。
例如,以下程序从/dev/urandom
读取400000000字节:
#include <time.h>
#include <sys/times.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
struct tms time_end;
void handle() {
times(&time_end);
}
int main(int argc, char *argv[]) {
signal(SIGINT, handle);
// read from urandom so that kernel has to generate randomness
FILE *f = fopen("/dev/urandom", "r");
for (int i = 0; i < 20000000; ++i) {
char buf[20];
fread(buf, sizeof(buf), 1, f);
}
fclose(f);
pause();
printf("tms_stime = %ld\n", (long)time_end.tms_stime);
return 0;
}
另存为1.c
文件并在我的系统上的shell输出中执行:
$ sh -c 'gcc 1.c ; ./a.out & child=$!; sleep 2; kill -INT $child ; wait'
tms_stime = 127
在linux上,您可能也会对CLOCK_PROCESS_CPUTIME_ID
感兴趣。