将毫秒转换为 GNU 端口的时间规范

标签 c linux datetime gnu timespec

我想将毫秒转换为 GNU Linux 使用的 timespec 结构。我已尝试使用相同的代码。

  timespec GetTimeSpecValue(unsigned long milisec)
  {
    struct timespec req;
    //long sec = (milisecondtime /1000);
    time_t sec = (time_t)(milisec/1000);
    req->tv_sec = sec;
    req->tv_nsec = 0;
    return req;
  }

运行此代码会出现以下错误。

expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘GetTimeSpecValue’

我还在代码中包含了 time.h 文件。

最佳答案

timespec 结构以两部分表示时间——秒和纳秒。因此,从毫秒转换的算法非常简单。一秒有千毫秒,一毫秒有千微秒,一微秒有千纳秒,为此我们感谢 SI .因此,我们首先需要将毫秒除以一千来得到秒数。例如,1500 毫秒/1000 = 1.5 秒。给定整数运算(不是 float ),余数将被删除(即 1500/1000 只等于 1,而不是 1.5)。然后我们需要取一个表示一定小于一秒的毫秒数的余数,并将其乘以一百万以将其转换为纳秒。为了得到除以 1000 的余数,我们使用 module operator (%) (即 1500 % 1000 等于 500)。例如,让我们将 4321 毫秒转换为秒和纳秒:

  1. 4321(毫秒)/1000 = 4(秒)
  2. 4321(毫秒)% 1000 = 321(毫秒)
  3. 321(毫秒)* 1000000 = 321000000(纳秒)

知道了以上这些,剩下的就是写一点C代码了。有几件事你没有做对:

  1. 在 C 中,您必须使用 struct 作为结构数据类型的前缀。例如,不是说 timespec,而是说 struct timespec。然而,在 C++ 中,您不必这样做(不幸的是,在我看来)。
  2. 您不能从 C 中的函数返回结构。因此,您需要通过指针将结构传递给使用该结构执行某些操作的函数。

编辑:这与 ( Return a `struct` from a function in C) 相矛盾。

好了,废话不多说了。下面是一个简单的 C 代码示例:

#include <time.h>
#include <stdlib.h>
#include <stdio.h>

static void ms2ts(struct timespec *ts, unsigned long ms)
{
    ts->tv_sec = ms / 1000;
    ts->tv_nsec = (ms % 1000) * 1000000;
}

static void print_ts(unsigned long ms)
{
    struct timespec ts;
    ms2ts(&ts, ms);
    printf("%lu milliseconds is %ld seconds and %ld nanoseconds.\n",
           ms, ts.tv_sec, ts.tv_nsec);
}

int main()
{
    print_ts(1000);
    print_ts(2500);
    print_ts(4321);
    return EXIT_SUCCESS;
}

希望对您有所帮助。祝你好运!

关于将毫秒转换为 GNU 端口的时间规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15024623/

相关文章:

c# - 为什么 DateTime 不是预定义类型?

python - 神秘时间转换( Pandas 和日期时间)

datetime - Ansible - 将日期增加 'X' 天/分钟

c - 怎么了? C

python - gobject 的 pydev 问题

linux - 为什么简单的退出程序不起作用?

带有 sudo 的 Java 包装器脚本不起作用

c - 如何将一维数组从 fortran 传递到 c

c++ - 如何在 Visual C++ 中使用 lstrcat 进行连接?

c - 在同一系统上运行基于 Unix 的可执行文件