【问题标题】:How to measure the time in seconds between two characters while user inserting them as an input如何在用户将它们作为输入插入时测量两个字符之间的时间(以秒为单位)
【发布时间】: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


【解决方案1】:
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 Elapsed Time

【讨论】:

  • 注意:这里不需要(double) 演员表。
【解决方案2】:

在我的系统上使用 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);

【讨论】:

  • 我认为这与您使用标准 C 库一样准确。
  • "%i" 不一定匹配 clock_tCLOCKS_PER_SEC 可能不是整数类型。建议printf("%lld %g\n",(long long) (c2-c1),(double)CLOCKS_PER_SEC);
猜你喜欢
  • 2020-02-22
  • 2020-08-03
  • 2014-02-26
  • 1970-01-01
  • 2011-05-17
  • 2016-05-14
  • 2020-09-29
  • 2015-10-17
  • 2012-12-03
相关资源
最近更新 更多