0

如何以秒为单位测量插入时间?

我尝试使用:

struct timeval t1,t2;

我在插入输入之前检查了时间:

gettimeofday(&t1,NULL);

得到输入后也是一样的:

gettimeofday(&t2,NULL);
double elapsedTime=(t2.tv_sec - t1.tv_sec)*10000.0;

但它根本不准确!

我需要更好的方法来测量Inserting time中的秒数,并了解插入每个字符的秒数差异。

// 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
4

2 回答 2

2
elapsedTime=(t1.tv_sec - t2.tv_sec)*10000.0;

您只考虑 tv_sec 。实际的 timeval 结构有一个tv_sec和一个tv_usec部分,它们都是不包含分数的整数(虽然不能保证确切的类型)

tv_sec 保存秒,tv_usec 保存微秒。

它还保证 tv_usec 始终小于 1000000,这意味着您只需要单独计算它们的差异。

而且你也在做 t1-t2 你应该把它改成 t2-t1 因为 t2 是最新的时间。这就是为什么你会变得消极的原因。

elapsedTime=((double) (t2.tv_sec - t1.tv_sec))+((double) (t2.tv_usec - t1.tv_usec) / 1000000.0);

它以“sec.usec”格式返回时间,应该足够精确:)

请注意,您需要将 elapsedTime 声明为 double 而不是 int,并将 printf 中的第二个“$d”替换为“%f”。

您还需要考虑键盘输入是缓冲的,这意味着您在 getchar() 中被阻塞,直到按下 Enter,然后将缓冲区馈送到 getchar,一次调用一个字符。您 cad 只使用 Enter 作为输入字符来测试代码的准确性,但要将其与实际字符一起使用,您需要使用无缓冲输入。

GNU 文档:21.2 已用时间

于 2019-06-21T18:58:29.733 回答
0

在我的系统上使用 clock() 以毫秒为单位计数,也许这对于您的目的来说已经足够准确了:

#include "time.h"

clock_t c1=clock();
... doing stuff ...
clock_t c2=clock();
printf("diff %i clocks with CLOCKS_PER_SEC = %i\n",c2-c1,CLOCKS_PER_SEC);
于 2019-06-21T18:55:35.070 回答