【问题标题】:what is the error in the below code of c timestamp?以下c时间戳代码中的错误是什么?
【发布时间】:2014-05-22 08:26:01
【问题描述】:
double GetTimeStamp()
{
    struct timespec start;

    if((clock_gettime( CLOCK_MONOTONIC, &start)) == -1 )
    {
        perror("clock gettime\n");
    }

    return start.tv_sec + start.tv_nsec * 1e-9;   //seconds
}

MAIN.c:

uint64_t Receive;
uint32 receiveTime;
int main()
{
    rc=recvfrom(sock, buf, 256, 0, (struct sockaddr*) &client, &len);
    Receive = GetTimeStamp();
    receiveTime = (uint32) (Receive / 1000000);    // I am converting to microseconds
    printf("Receive time: %lu\n", receiveTime);
}

我正在获取时间戳并从另一个程序中读取该时间,如上所示。但是,如果我按照上述方式进行操作,我将得不到任何价值。为什么 main 中没有显示任何值?

【问题讨论】:

  • 您确实转换为 int,这确实切断了小数点后的所有内容。所以如果你有 1 秒 -> (int)(1/ 100000) = 0
  • 那么解决方案是什么? double 将是一个非常大的值。
  • 哦,我刚刚注意到你的转换还是很糟糕。 nano_seconds 到秒是nano_seconds / 1e-9;,秒到微秒是:seconds * 1e6
  • 如果你真的想打印你实际拥有的东西:double receiveTime = 1.000000555; printf("Receive time: %0.8f\n", receiveTime)
  • 1) 虽然我怀疑这是你的问题,printf("Receive time: %lu\n", receiveTime); 是 UB。应该是printf("Receive time: %" PRIu32 "\n", receiveTime);。 2) 确定代码从recvfrom()返回?

标签: c linux timestamp clock qnx


【解决方案1】:

由

I am not getting any value if I do as above. Why is it not displaying any value in main?

你的意思是显示0,还是什么都不显示?

假设是前者,CLOCK_MONOTONIC 默认在启动时启动 (Starting point for CLOCK_MONOTONIC),因此它测量系统的正常运行时间。现在,您的 GetTimeStamp 代码将自引导时间以来的秒数返回为双精度数,然后您将其除以 1,000,000,并带有不正确的注释“我正在转换为微秒”。事实上,您将自启动以来的秒数除以 100 万,因此这可能会返回 0,除非您的系统已启动超过 1,000,000 秒。那将超过11天。因此,如果您的系统启动时间少于此时间,您可能会一直看到 0 作为输出。

假设是后者,您的 recvfrom 调用可能会阻塞。您可以通过将其注释掉并看到代码至少产生输出来验证这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多