时间问,以微秒,但在几秒钟 [英] Time asked in microseconds but got in seconds

查看:145
本文介绍了时间问,以微秒,但在几秒钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读Ubuntu下的系统时间时遇到了一些问题。我试图得到两个ptime变量的区别。

I am having some problem by reading out the system time under Ubuntu. I am trying to get the difference of two ptime variables.

这是我的声明:

#include "boost/date_time/posix_time/posix_time.hpp"

boost::posix_time::ptime now  = boost::posix_time::microsec_clock::universal_time();
boost::posix_time::ptime last_time = now;
boost::posix_time::time_duration dt;
...

一段时间后,我更新now变量, p>

After a time I update the now variable and build the difference

now  = boost::posix_time::second_clock::universal_time();
dt = last_time - now;

问题是,我想在我的项目中以毫秒的分辨率工作,

The problem is that I want to work in millisecond resolution in my project so I divide the time I get by 1000 (after converting the time to microseconds like below).

printf("%f", (double)dt.total_microseconds());

问题是我只得到第二个分辨率的值。我已经尝试了local_time(),而不是universal_time()。它没有解决我的问题...

The problem is that I only got values in second resolution. I already tried local_time() instead of universal_time(). It did not solved my problem...

有没有人有任何建议?

帮助。

推荐答案

对于C ++ 11方式,请检查回答 bames53。

For the C++11 way, check the answer of bames53.

这以时间单位为纳秒。在Ubuntu,C ++中,您需要将-lrt添加到链接的库列表。示例(在mainfile中):

This gives the time in nanoseconds. In Ubuntu, C++, you need to add -lrt to the list of libraries you link to. Example (in a mainfile):

mm:main.cpp memory_manager.cc

mm: main.cpp memory_manager.cc

g ++ -Wextra -Wall -Wreorder -o mm main.cpp memory_manager.cc -lrt

g++ -Wextra -Wall -Wreorder -o mm main.cpp memory_manager.cc -lrt

#include <cstdint> // C++11. Use #include <stdint.h> instead
#include <ctime>

int64_t timespecDiff(struct timespec *timeA_p, struct timespec *timeB_p)
{
  return (((int64_t)timeA_p->tv_sec * 1000000000) + timeA_p->tv_nsec) -
         (((int64_t)timeB_p->tv_sec * 1000000000) + timeB_p->tv_nsec);
}

struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);

/* Code to be measured */

clock_gettime(CLOCK_MONOTONIC, &end);
int64_t time;
time = timespecDiff(&end, &start);
std::cout<<"Time: " << time << " ns\n";

然后转换为ms。

请参阅我的示例此处

另一个有趣的方法是,你可能想要的是:

Another interesting approach, that might be a bit off for what you want is this:

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
    struct timeval start, end;

    long mtime, seconds, useconds;    

    gettimeofday(&start, NULL);
    usleep(2000);
    gettimeofday(&end, NULL);

    seconds  = end.tv_sec  - start.tv_sec;
    useconds = end.tv_usec - start.tv_usec;

    mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;

    printf("Elapsed time: %ld milliseconds\n", mtime);

    return 0;
}

来源

这篇关于时间问,以微秒,但在几秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆