【问题标题】:How can I use clock_gettime to calculate the total time it takes for a command如何使用 clock_gettime 计算命令所需的总时间
【发布时间】:2021-12-04 05:11:00
【问题描述】:

我对如何操作从clock_gettime 获得的值的细节有点问题。我想计算一个可执行文件/命令的总运行时间。

我希望以(例如 3.475 秒)的格式打印出实时 我快完成了,但我很确定它不会以我想要的格式返回。我怎么能这样做?

  struct timespec tsstart, tsend;
  clock_gettime(CLOCK_MONOTONIC, &tsstart);
  //execuatble/command executes and finishes
  clock_gettime(CLOCK_MONOTONIC, &tsend);
  long long realtime = (tsend.tv_sec-tsstart.tv_sec)*1000000LL + tsend.tv_usec-tsstart.tv_usec;
  printf("real: %.3lds, ", realtime);

每当我尝试运行它时,在短时间内(即

35273s

如何将输出格式更改为 3d.p。我需要的精度?

【问题讨论】:

  • 嗯,标准 C 具有 struct timespec“它保存以秒和 纳秒 为单位指定的间隔 ...”和成员 long tv_nsec。好奇的linux使用.tv_usec
  • 使用long long realtime,我希望"%.3lld",而不是"%.3ld"
  • @chux-ReinstateMonica,是的,这也是我发现的一个错误,我把它搞砸了,因为我同时使用 rusage,但是对于这个,它会是 .tv_nsec
  • @chux-ReinstateMonica 至于%.3ld 是的,有点类型不匹配,但不是问题
  • needshelpwithcoding "little bit of a type mismatch" 意味着您没有在编译时启用所有警告。因此,您没有完全使用第一个可用的有效资产 - 您的编译器。为自己和其他人节省时间,作为一种职业礼貌。

标签: c linux operating-system


【解决方案1】:

将缩放的 long long 整数 (*1000000LL) 更改为 x.xxxxxx 输出

printf("%s%lld.%06lld", 
    realtime < 0 ? "-" : "", 
    llabs(realtime/1000000), 
    llabs(realtime%1000000));

棘手的情况包括[-999999 ... -1] 中的realtime 值。当然,这些值不是预期的时间减法。

如果我们假设 realtime &gt;= 0,那么

printf("%lld.%06lld", 
    realtime/1000000, realtime%1000000);

要折腾低三位:

// Form rounded quotient of milliseconds
long long ms = realtime/1000 + (realtime%1000 >= 500);
printf("%lld.%03lld", ms/1000, ms%1000);

【讨论】:

    【解决方案2】:
      struct timespec tsstart, tsend;
      clock_gettime(CLOCK_MONOTONIC, &tsstart);
      //execuatble/command executes and finishes
      clock_gettime(CLOCK_MONOTONIC, &tsend);
      float realtime = (tsend.tv_sec-tsstart.tv_sec)+(tsend.tv_nsec-tsstart.tv_nsec)/1000000000.0;
      printf("real: %.3fs, ", realtime);
    

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    猜你喜欢
    • 2021-04-04
    • 2020-10-17
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 2021-11-06
    • 2012-12-06
    • 1970-01-01
    相关资源
    最近更新 更多