[英]How to get a Unix timestamp for C (in double or float)
How can I get a Unix time stamp for C, specifically showing decimal places. 如何获得C的Unix时间戳,具体显示小数位。 All the answers I have found elsewhere return an integer. 我在其他地方找到的所有答案都返回一个整数。
The time()
function returns an integer only. time()
函数仅返回整数。 Both gettimeofday()
and clock_gettime()
return structures (different structures) with seconds and subseconds (microseconds for gettimeofday()
and nanoseconds for clock_gettime()
). gettimeofday()
和clock_gettime()
返回具有秒和亚秒数的结构(不同的结构)( gettimeofday()
为微秒, clock_gettime()
为纳秒)。 You'd have to do an appropriate (but simple) computation to return that as a double
. 您必须进行适当(但简单)的计算才能将其作为double
返回。
There's no point in returning a current Unix timestamp as a float
; 将当前的Unix时间戳作为float
返回是没有意义的; you'd only get values accurate to a couple of minutes or so. 您只会获得精确到几分钟左右的值。
POSIX has officially deprecated gettimeofday()
. POSIX已正式弃用gettimeofday()
。 However, Mac OS X for one does not have clock_gettime()
, so you're likely to find gettimeofday()
is more widely available. 但是,Mac OS X并没有clock_gettime()
,因此您很可能会发现gettimeofday()
范围更广。
#include <time.h>
#include <stdio.h>
int main(void)
{
long t0 = time(0);
float f0 = t0;
float f1;
float f2;
long d_pos = 0;
long d_neg = 0;
while ((f1 = t0 + d_pos) == f0)
d_pos++;
while ((f2 = t0 + d_neg) == f0)
d_neg--;
printf("t0 = %ld; f0 = %12.0f; d_pos = %ld (f1 = %12.0f); d_neg = %ld (f2 = %12.0f)\n",
t0, f0, d_pos, f1, d_neg, f2);
return 0;
}
Sample output: 样本输出:
t0 = 1385638386; f0 = 1385638400; d_pos = 79 (f1 = 1385638528); d_neg = -51 (f2 = 1385638272)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.