我想测量从启动进程到使用C SIGINT
函数发送times
信号之间经过的CPU和用户时间。
但是,在印刷中,我只得到0
。看不到问题..
15 struct tms time_start;
16 struct tms time_end;
17
18 clock_t start;
19 clock_t end;
20
21
22
23
24 void handle() {
25 times(&time_end);
26 end = time_end.tms_stime;
27 printf("%ld\n", end);
28 }
29
30
31
32
33 int main(int argc, char *argv[]) {
34
35 signal(SIGINT, handle);
36 times(&time_start);
37 start = time_start.tms_utime;
38 pause();
39
40 return 0;
41 }
根据评论进行编辑:
#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。看不到问题。。
tms_stime
是代表进程在内核中花费的CPU时间。 pause()
没有执行任何操作,因此它不占用CPU时间-您的程序没有执行任何操作。执行一些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