C编程语言中的时间戳

Chr*_*_45 23 c time timestamp

如何标记t1和t2两次并获得C中的毫秒差异?

Ark*_*nez 30

这将为您提供以秒为单位的时间+微秒

#include <sys/time.h>
struct timeval tv;
gettimeofday(&tv,NULL);
tv.tv_sec // seconds
tv.tv_usec // microseconds
Run Code Online (Sandbox Code Playgroud)


Chr*_*oph 9

标准C99:

#include <time.h>

time_t t0 = time(0);
// ...
time_t t1 = time(0);
double datetime_diff_ms = difftime(t1, t0) * 1000.;

clock_t c0 = clock();
// ...
clock_t c1 = clock();
double runtime_diff_ms = (c1 - c0) * 1000. / CLOCKS_PER_SEC;
Run Code Online (Sandbox Code Playgroud)

类型的精度是实现定义的,即日期时间差异可能仅返回整秒.

  • @pmg:精度是实现定义的,例如在我的系统上`time()`具有`1s`分辨率; `clock()`的精度通常尽可能高,但它测量运行时间而不是日期时间 (2认同)

dar*_*ron 6

如果要查找已用时间,只要不在开始和结束之间重新启动计算机,此方法就会起作用.

在Windows中,使用GetTickCount().这是如何做:

DWORD dwStart = GetTickCount();
...
... process you want to measure elapsed time for
...
DWORD dwElapsed = GetTickCount() - dwStart;
Run Code Online (Sandbox Code Playgroud)

dwElapsed现在是经过的毫秒数.

在Linux中,使用clock()CLOCKS_PER_SEC来做同样的事情.

如果您需要通过重新启动或跨PC(这确实需要非常好的同步)的时间戳,那么使用其他方法(gettimeofday()).

此外,在Windows中,至少可以比标准时间分辨率更好.通常情况下,如果你在一个紧凑的循环中调用GetTickCount(),你会发现它每次改变时都会跳跃10-50.这是因为Windows线程调度程序使用的时间量.这或多或少是它在切换到其他东西之前为每个线程运行的时间量.如果你这样做:

timeBeginPeriod(1);
Run Code Online (Sandbox Code Playgroud)

在您的计划或流程的开头和:

timeEndPeriod(1);
Run Code Online (Sandbox Code Playgroud)

最后,量子将变为1毫秒,你将在GetTickCount()调用上获得更好的时间分辨率.但是,这确实会对整个计算机的运行过程进行微妙的更改,因此请记住这一点.但是,无论如何,Windows Media Player和许多其他事情都会这样做,所以我不担心它.

我确信在Linux中可能有一些方法可以做同样的事情(可能有更好的控制,或者可能有亚毫秒量子),但我还不需要在Linux中这样做.


小智 6

/*
 Returns the current time.
*/

char *time_stamp(){

char *timestamp = (char *)malloc(sizeof(char) * 16);
time_t ltime;
ltime=time(NULL);
struct tm *tm;
tm=localtime(&ltime);

sprintf(timestamp,"%04d%02d%02d%02d%02d%02d", tm->tm_year+1900, tm->tm_mon, 
    tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
return timestamp;
}


int main(){

printf(" Timestamp: %s\n",time_stamp());
return 0;

}
Run Code Online (Sandbox Code Playgroud)

输出:时间戳:20110912130940 // 2011年9月12日13:09:40