简体   繁体   English

C 编程语言中的时间戳

[英]Time stamp in the C programming language

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

This will give you the time in seconds + microseconds这将为您提供秒 + 微秒的时间

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

Standard C99:标准 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;

The precision of the types is implementation-defined, ie the datetime difference might only return full seconds.类型的精度是实现定义的,即日期时间差异可能只返回完整的秒数。

If you want to find elapsed time, this method will work as long as you don't reboot the computer between the start and end.如果您想查找经过的时间,只要您在开始和结束之间不重新启动计算机,此方法就可以使用。

In Windows, use GetTickCount().在 Windows 中,使用 GetTickCount()。 Here's how:就是这样:

DWORD dwStart = GetTickCount();
...
... process you want to measure elapsed time for
...
DWORD dwElapsed = GetTickCount() - dwStart;

dwElapsed is now the number of elapsed milliseconds. dwElapsed现在是经过的毫秒数。

In Linux, use clock() and CLOCKS_PER_SEC to do about the same thing.在 Linux 中,使用clock()CLOCKS_PER_SEC来做同样的事情。

If you need timestamps that last through reboots or across PCs (which would need quite good syncronization indeed), then use the other methods (gettimeofday()).如果您需要通过重新启动或跨 PC 持续的时间戳(这确实需要非常好的同步),然后使用其他方法(gettimeofday())。

Also, in Windows at least you can get much better than standard time resolution.此外,至少在 Windows 中,您可以获得比标准时间分辨率更好的分辨率。 Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed.通常,如果您在一个紧密的循环中调用 GetTickCount(),您会看到它每次更改时都会跳跃 10-50。 That's because of the time quantum used by the Windows thread scheduler.这是因为 Windows 线程调度程序使用的时间量。 This is more or less the amount of time it gives each thread to run before switching to something else.这或多或少是每个线程在切换到其他线程之前运行的时间。 If you do a:如果您执行以下操作:

timeBeginPeriod(1);

at the beginning of your program or process and a:在您的计划或流程开始时,以及:

timeEndPeriod(1);

at the end, then the quantum will change to 1 ms, and you will get much better time resolution on the GetTickCount() call.最后,量程将更改为 1 毫秒,您将在 GetTickCount() 调用中获得更好的时间分辨率。 However, this does make a subtle change to how your entire computer runs processes, so keep that in mind.但是,这确实对整个计算机运行进程的方式产生了微妙的变化,因此请记住这一点。 However, Windows Media Player and many other things do this routinely anyway, so I don't worry too much about it.但是,无论如何,Windows Media Player 和许多其他东西都会定期执行此操作,因此我不必太担心。

I'm sure there's probably some way to do the same in Linux (probably with much better control, or maybe with sub-millisecond quantums) but I haven't needed to do that yet in Linux.我确信在 Linux 中可能有一些方法可以做同样的事情(可能有更好的控制,或者亚毫秒量子),但我还不需要在 Linux 中这样做。

/*
 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;

}

Output: Timestamp: 20110912130940 // 2011 Sep 12 13:09:40输出:时间戳:20110912130940 // 2011 Sep 12 13:09:40

Use @Arkaitz Jimenez's code to get two timevals:使用@Arkaitz Jimenez 的代码获得两个时间值:

#include <sys/time.h>
//...
struct timeval tv1, tv2, diff;

// get the first time:
gettimeofday(&tv1, NULL);

// do whatever it is you want to time
// ...

// get the second time:
gettimeofday(&tv2, NULL);

// get the difference:

int result = timeval_subtract(&diff, &tv1, &tv2);

// the difference is storid in diff now.

Sample code for timeval_subtract can be found at this web site :可以在此网站上找到 timeval_subtract 的示例代码:

 /* Subtract the `struct timeval' values X and Y,
    storing the result in RESULT.
    Return 1 if the difference is negative, otherwise 0.  */

 int
 timeval_subtract (result, x, y)
      struct timeval *result, *x, *y;
 {
   /* Perform the carry for the later subtraction by updating y. */
   if (x->tv_usec < y->tv_usec) {
     int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
     y->tv_usec -= 1000000 * nsec;
     y->tv_sec += nsec;
   }
   if (x->tv_usec - y->tv_usec > 1000000) {
     int nsec = (x->tv_usec - y->tv_usec) / 1000000;
     y->tv_usec += 1000000 * nsec;
     y->tv_sec -= nsec;
   }

   /* Compute the time remaining to wait.
      tv_usec is certainly positive. */
   result->tv_sec = x->tv_sec - y->tv_sec;
   result->tv_usec = x->tv_usec - y->tv_usec;

   /* Return 1 if result is negative. */
   return x->tv_sec < y->tv_sec;
 }

how about this solution?这个解决方案怎么样? I didn't see anything like this in my search.我在搜索中没有看到类似的内容。 I am trying to avoid division and make solution simpler.我试图避免分裂并使解决方案更简单。

   struct timeval cur_time1, cur_time2, tdiff;

   gettimeofday(&cur_time1,NULL);
   sleep(1);
   gettimeofday(&cur_time2,NULL);

   tdiff.tv_sec = cur_time2.tv_sec - cur_time1.tv_sec;
   tdiff.tv_usec = cur_time2.tv_usec + (1000000 - cur_time1.tv_usec);

   while(tdiff.tv_usec > 1000000)
   {
      tdiff.tv_sec++;
      tdiff.tv_usec -= 1000000;
      printf("updated tdiff tv_sec:%ld tv_usec:%ld\n",tdiff.tv_sec, tdiff.tv_usec);
   }

   printf("end tdiff tv_sec:%ld tv_usec:%ld\n",tdiff.tv_sec, tdiff.tv_usec);

Also making aware of interactions between clock() and usleep().还要注意clock() 和usleep() 之间的交互。 usleep() suspends the program, and clock() only measures the time the program is running. usleep() 挂起程序,clock() 只测量程序运行的时间。

If might be better off to use gettimeofday() as mentioned here如果使用这里提到的 gettimeofday() 可能会更好

使用gettimeofday()或更好的clock_gettime()

U can try routines in c time library ( time.h ).你可以在 c 时间库( time.h )中尝试例程。 Plus take a look at the clock() in the same lib.另外看看同一个库中的clock() It gives the clock ticks since the prog has started.它给出了自编开始以来的时钟滴答声。 But you can save its value before the operation you want to concentrate on, and then after that operation capture the cliock ticks again and find the difference between then to get the time difference.但是你可以在你想要专注的操作之前保存它的值,然后在该操作之后再次捕获时钟刻度并找到它们之间的差异以获得时间差。

time_t tm = time(NULL);
char time[4096];
ctime_r(&tm, time);
time[strlen(time) - 1] = '\0';
printf("%s",time);

Timestamp as: date --utc +%FT%T.%3NZ , in shell:时间戳为: date --utc +%FT%T.%3NZ ,在shell中:

char *time_stamp() {
    char *timestamp = (char *)malloc(sizeof(char) * 25);
    char *nanos = (char *)malloc(sizeof(char) * 12);
    //time_t ltime;
    //ltime=time(NULL);

    struct tm *tm;
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);

    tm=localtime(&ts.tv_sec);
    sprintf(nanos, "%ld", ts.tv_nsec); 

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM