为timeval C ++添加毫秒

时间:2017-04-19 09:09:06

标签: c++ linux ubuntu timeval

下面的代码我可以用毫秒获得当前时间。现在我想为系统时间添加毫秒。任何提示?

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
    struct timeval time;
    gettimeofday (&time, NULL);

    long systemtime = time.tv_sec*1000L + time.tv_usec/1000L;

     printf("Time in milliseconds: %ld milliseconds\n", systemtime);
     //sample output: 1492592522106

     return 0;
}

编辑:已解决

#include <stdio.h>
#include <sys/time.h>

int main (int argc, char** argv) {
    struct timeval time;
    gettimeofday (&time, NULL);

    printf("Time in milliseconds: %ld milliseconds\n", time.tv_sec*1000L + 
    (time.tv_usec/1000L));
    printf("Time in milliseconds+300: %ld milliseconds\n", time.tv_sec*1000L 
    + (time.tv_usec/1000L+300));
    printf("usec: %ld", time.tv_usec/1000L);

    return 0;
}

输出:

Time in milliseconds: 1492595580965 milliseconds (Wed, 19 Apr 2017 09:53:00.965 GMT)
Time in milliseconds+300: 1492595581265 milliseconds (Wed, 19 Apr 2017 09:53:01.265 GMT)
usec: 965

2 个答案:

答案 0 :(得分:4)

您可以使用std::chrono库来执行此任务。 以下代码段将为您提供帮助,

auto now = std::chrono::system_clock::now().time_since_epoch();
auto t100ms = std::chrono::milliseconds(100);
auto time = now + t100ms;
std::cout << std::chrono::duration_cast<std::chrono::milliseconds>(time).count();

答案 1 :(得分:-1)

你试过adjtime()吗? 。 http://man7.org/linux/man-pages/man3/adjtime.3.html