我的代码如下所示:
#include <time.h>
#include <stdio.h>
#include <unistd.h>
int main(void) {
time_t loop_begin, loop_end, scanf_begin, scanf_end;
double loop_time, scanf_time;
int q;
loop_begin = clock();
//some big loop
loop_end = clock();
loop_time = (double)(loop_end - loop_begin) / CLOCKS_PER_SEC;
printf("%.6f\n", loop_time);
scanf_begin = clock();
printf("qwe> ");scanf("%d", &q);
scanf_end = clock();
scanf_time = (double)(scanf_end - scanf_begin) / CLOCKS_PER_SEC;
printf("%.6f\n", scanf_time);
return 0;
}
但是输出是这样的:
20.087593
qwe> 543
0.000073
我错过了什么还是这正常?如果这是正常的,您有什么建议?
最佳答案
clock
测量 CPU 时间。当您的程序等待按键时,它会在系统调用中被阻止,并且不会使用任何处理器时间。
来自 Linux 程序员手册:
NAME
clock
- determine processor timeSYNOPSIS
#include <time.h> clock_t clock(void);
DESCRIPTION
The clock() function returns an approximation of processor time used by the program.
RETURN VALUE
The value returned is the CPU time used so far as a
clock_t
; to get the number of seconds used, divide byCLOCKS_PER_SEC
. If the processor time used is not available or its value cannot be represented, the function returns the value(clock_t) -1.
关于时钟()无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36091472/