[英]C/C++ time_t in microseconds
This program returns the time in seconds. 该程序以秒为单位返回时间。 I need to return it in microseconds .
我需要在几微秒内返回它。
time_t timeStart = time(0);
usleep(2.5e6);
time_t timeEnd = time(0);
float R = (timeEnd - timeStart);
std::cout << R << std::endl;
If you're looking for a higher resolution, you can use std::chrono::high_resolution_clock
from C++11. 如果您正在寻找更高的分辨率,可以使用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;
Outputs something like 输出类似的东西
It took me 0.091001 seconds.
Example from http://www.cplusplus.com/reference/chrono/high_resolution_clock/now/ 来自http://www.cplusplus.com/reference/chrono/high_resolution_clock/now/的示例
using function gettimeofday 使用函数gettimeofday
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)): glibc的功能测试宏要求(参见feature_test_macros(7)):
settimeofday(): _BSD_SOURCE
Description 描述
The functions gettimeofday()
and settimeofday()
can get and set the time as well as a timezone. gettimeofday()
和settimeofday()
函数可以获取和设置时间以及时区。 The tv argument is a struct timeval
(as specified in ): tv参数是一个
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)). 并给出自纪元以来的秒数和微秒数(见时间(2))。 The tz argument is a
struct timezone
: tz参数是一个
struct timezone
:
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
this function can get microsecond 这个功能可以达到微秒
Take a look at the std::chrono
header. 看一下
std::chrono
标题。 It contains many different options for time manipulation, including the ability to convert to microseconds
via std::chrono::duration_cast
. 它包含许多不同的时间操作选项,包括通过
std::chrono::duration_cast
转换为microseconds
的能力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.