8

我想将毫秒转换为 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;
  }

运行此代码会给我以下错误。

'GetTimeSpecValue' 之前应为 '='、','、';'、'asm' 或 '__attribute__'</p>

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

4

3 回答 3

12

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

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

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

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

编辑:这与(从 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;
}

希望能帮助到你。祝你好运!

于 2013-02-22T14:27:06.883 回答
1

试试这个:

struct timespec GetTimeSpecValue(unsigned long millisec) {
    struct timespec req;
    req.tv_sec=  (time_t)(millisec/1000);
    req.tv_nsec = (millisec % 1000) * 1000000;
    return req;
}

我不认为 struct timespec 是 typedef 的,因此您需要在 timespec 前面加上 struct。如果你想精确的话,计算出纳秒部分。请注意, req 不是指针。因此不能使用'->'访问成员

于 2013-02-22T13:17:45.210 回答
0

对答案进行了一些调整,包括 Geoffrey 的评论,下面的代码避免了小延迟的除法和长延迟的模数:

void msec_to_timespec(unsigned long msec, struct timespec *ts)
{
    if (msec < 1000){
        ts->tv_sec = 0;
        ts->tv_nsec = msec * 1000000;
    }
    else {
        ts->tv_sec = msec / 1000;
        ts->tv_nsec = (msec - ts->tv_sec * 1000) * 1000000;
    }
}
于 2019-03-17T13:01:04.710 回答