【发布时间】:2019-06-21 18:33:13
【问题描述】:
如何以秒为单位测量插入时间?
我尝试使用:
struct timeval t1,t2;
我在插入输入之前检查了时间:
gettimeofday(&t1,NULL);
得到输入后也是这样:
gettimeofday(&t2,NULL);
double elapsedTime=(t2.tv_sec - t1.tv_sec)*10000.0;
但这一点都不准确!!
我需要更好的方法来测量 插入时间 中的秒数,并了解插入每个字符的秒数差异。
// trying to insert 5 chars
for(i=0; i<=4 ; i++)
{
gettimeofday(&t1,NULL); //get time before getting char
c=getchar();
gettimeofday(&t2,NULL); //get time after geting char
elapsedTime=(t1.tv_sec - t2.tv_sec)*10000.0;
printf("\n char number %d his elapsed time =%d\n",i,elapsedTime);
}
我需要知道秒率,插入“点击”字符作为输入,并以秒为单位计算elapsedTime:
输出应该是这样的:
time between inserting first character and the second is : 0.002 seconds
time between..........second character and the third is: 1.008 seconds
【问题讨论】:
-
你在循环代码 sn-p 中的减法是从后到前的,因为
t2晚于t1,因此更大。 -
"如何以秒为单位测量插入时间?"不要乘以
10000,还要考虑另一个struct成员suseconds_t tv_usec; /* microseconds */。 -
键盘输入被缓冲。您仅在按 Enter 键后收到字符。 (注意:缓冲输入允许用户在按下 Enter 之前编辑输入。)
-
@WeatherVane 好主意,谢谢,我试过了,我开始得到不同的结果,但我也得到了负数,怎么可能是负 useconds ?,(在 t1 和我之后仍然是 t2认为它也计算循环中的命令)
-
您需要将终端置于非规范模式。 Here's some code 适用于 MacOS。它也应该可以在 Linux 上运行。
标签: c linux time.h gettimeofday