C语言中Java的等价物是什么System.currentTimeMillis()
?
5 回答
检查time.h
,也许类似于gettimeofday()
功能。
你可以做类似的事情
struct timeval now;
gettimeofday(&now, NULL);
now.tv_sec
然后,您可以通过从和获取值来提取时间now.tv_usec
。
在 Linux 和其他类 Unix 系统上,您应该使用clock_gettime(CLOCK_MONOTONIC)。如果这不可用(例如 Linux 2.4),您可以退回到gettimeofday()。后者的缺点是受时钟调整的影响。
在 Windows 上,您可以使用QueryPerformanceCounter()。
我的这段代码将上述所有内容抽象为一个简单的接口,该接口以 int64_t 形式返回毫秒数。请注意,返回的毫秒值仅用于相对用途(例如超时),与任何特定时间无关。
#include <sys/time.h>
/**
* @brief provide same output with the native function in java called
* currentTimeMillis().
*/
int64_t currentTimeMillis() {
struct timeval time;
gettimeofday(&time, NULL);
int64_t s1 = (int64_t)(time.tv_sec) * 1000;
int64_t s2 = (time.tv_usec / 1000);
return s1 + s2;
}
我像System.currentTimeMillis()
在 Java 中一样编写此函数,并且它们具有相同的输出。
有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()更为常见。
看到这个线程:http ://cboard.cprogramming.com/c-programming/51247-current-system-time-milliseconds.html
它说 time() 函数精确到秒,更深的精度需要其他库......