2012-04-11 68 views
6

Java的System.currentTimeMillis()在C中的等价性是什么?获取C中的当前时间(以毫秒为单位)?

+4

什么操作系统? – 2012-04-11 00:48:52

+1

请参阅http://stackoverflow.com/questions/5303751/current-microsecond-time-in-c。那里的答案很好。 – netcoder 2012-04-11 00:57:10

+1

的可能的复制[如何衡量使用ANSI C的毫秒时间?(http://stackoverflow.com/questions/361363/how-to-measure-time-in-milliseconds-using-ansi-c) – 2016-03-18 22:50:35

回答

2

检查time.h,或许有点像gettimeofday()功能。

你可以做这样的事情

struct timeval now; 
gettimeofday(&now, NULL); 

然后你就可以从now.tv_secnow.tv_usec获取值提取时间。

+1

,但 2016-03-23 07:59:23

1

还有的time()功能,但它返回秒,不毫秒。如果您需要更高的精度,则可以使用Windows'GetSystemTimeAsFileTime()或* nix的gettimeofday()等特定于平台的功能。

如果你不真正关心的日期和时间,但只是想不想来一次两个事件之间的时间间隔,就像这样:

long time1 = System.currentTimeMillis(); 
// ... do something that takes a while ... 
long time2 = System.currentTimeMillis(); 
long elapsedMS = time2 - time1; 

那么C相当于是clock()。在Windows上,为此使用GetTickCount()更为常见。

3

在Linux和其他类Unix系统,你应该使用clock_gettime(CLOCK_MONOTONIC)。如果不可用(例如Linux 2.4),则可以回退到gettimeofday()。后者的缺点是受时钟调整的影响。

在Windows上,你可以使用QueryPerformanceCounter()

This code抽象所有上述的进一个简单的接口,它返回毫秒作为的int64_t的数量。请注意,返回的毫秒值仅用于相对使用(例如超时),并且不相对于任何特定时间。

+0

'CLOCK_MONOTONIC'与java函数不完全等价,因为java函数也受到wallclock调整的影响。当然,这是间隔定时器的正确选择,但是如果OP需要一个挂钟时间,它不会起作用。 – bdonlan 2012-05-05 06:25:45

相关问题