C / C ++ time_t,以微秒为单位

时间:2015-06-15 15:24:28

标签: c++ c seconds time-t

此程序以秒为单位返回时间。我需要在微秒中返回它。你能救我吗?

    time_t timeStart = time(0);
    usleep(2.5e6);
    time_t timeEnd = time(0);

    float R = (timeEnd - timeStart);
    std::cout << R << std::endl;

3 个答案:

答案 0 :(得分:1)

查看std::chrono标题。它包含许多不同的时间操作选项,包括通过microseconds转换为std::chrono::duration_cast的功能。

答案 1 :(得分:1)

如果您正在寻找更高的分辨率,可以使用C ++ 11中的std::chrono::high_resolution_clock

#include <chrono>

using namespace std::chrono;

high_resolution_clock::time_point t1 = high_resolution_clock::now();

/* some extensive action... */
usleep(2.5e6);

high_resolution_clock::time_point t2 = high_resolution_clock::now();

duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

std::cout << "It took me " << time_span.count() << " seconds.";
std::cout << std::endl;

输出类似

的内容
It took me 0.091001 seconds.

来自http://www.cplusplus.com/reference/chrono/high_resolution_clock/now/

的示例

答案 2 :(得分:1)

使用函数gettimeofday

#include <sys/time.h>

   int gettimeofday(struct timeval *tv, struct timezone *tz);

   int settimeofday(const struct timeval *tv, const struct timezone *tz);

glibc的功能测试宏要求(参见feature_test_macros(7)):

   settimeofday(): _BSD_SOURCE

说明        gettimeofday()和settimeofday()函数可以获取和设置时间以及时区。电视参数是一个        struct timeval(如中所述):

       struct timeval {
           time_t      tv_sec;     /* seconds */
           suseconds_t tv_usec;    /* microseconds */
       };

   and gives the number of seconds and microseconds since the Epoch (see time(2)).  The tz argument is a struct timezone:

       struct timezone {
           int tz_minuteswest;     /* minutes west of Greenwich */
           int tz_dsttime;         /* type of DST correction */
       };

这个函数可以得到微秒