Dan*_*ing 93
这可以使用POSIXclock_gettime功能实现.
在POSIX的当前版本,gettimeofday被标记为已过时.这意味着它可能会从规范的未来版本中删除.鼓励应用程序编写者使用该clock_gettime函数而不是gettimeofday.
以下是如何使用的示例clock_gettime:
#define _POSIX_C_SOURCE 200809L
#include <inttypes.h>
#include <math.h>
#include <stdio.h>
#include <time.h>
void print_current_time_with_ms (void)
{
long ms; // Milliseconds
time_t s; // Seconds
struct timespec spec;
clock_gettime(CLOCK_REALTIME, &spec);
s = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds
if (ms > 999) {
s++;
ms = 0;
}
printf("Current time: %"PRIdMAX".%03ld seconds since the Epoch\n",
(intmax_t)s, ms);
}
Run Code Online (Sandbox Code Playgroud)
如果您的目标是测量经过的时间,并且您的系统支持"单调时钟"选项,那么您应该考虑使用CLOCK_MONOTONIC而不是CLOCK_REALTIME.
yad*_*dab 58
你必须做这样的事情:
struct timeval tv;
gettimeofday(&tv, NULL);
double time_in_mill =
(tv.tv_sec) * 1000 + (tv.tv_usec) / 1000 ; // convert tv_sec & tv_usec to millisecond
Run Code Online (Sandbox Code Playgroud)
Eri*_*ang 32
以下是获取当前时间戳的util函数,以毫秒为单位:
#include <sys/time.h>
long long current_timestamp() {
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // calculate milliseconds
// printf("milliseconds: %lld\n", milliseconds);
return milliseconds;
}
Run Code Online (Sandbox Code Playgroud)
关于时区:
gettimeofday()支持指定时区,我使用NULL,忽略时区,但如果需要,可以指定时区.
@Update - 时区
由于long时间的表示与时区本身无关或受其影响,因此设置tzgettimeofday()的参数不是必需的,因为它不会产生任何差别.
并且,根据手册页gettimeofday(),timezone结构的使用已经过时,因此tz通常应将参数指定为NULL,有关详细信息,请查看手册页.
C11 timespec_get
它返回最多纳秒,四舍五入到实现的分辨率.
它已在Ubuntu 15.10中实现.API看起来与POSIX相同clock_gettime.
#include <time.h>
struct timespec ts;
timespec_get(&ts, TIME_UTC);
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
Run Code Online (Sandbox Code Playgroud)
更多细节:https://stackoverflow.com/a/36095407/895245
| 归档时间: |
|
| 查看次数: |
232691 次 |
| 最近记录: |