C编程语言中的时间戳

时间:2022-07-31 16:05:53

How do I stamp two times t1 and t2 and get the difference in milliseconds in C?

我如何在两个t1和t2上加上戳,然后用C表示以毫秒为单位的差值?

9 个解决方案

#1


29  

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

#2


8  

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.

类型的精度是实现定义的,即datetime的差异可能只返回完整的秒。

#3


6  

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(). Here's how:

在Windows中,使用GetTickCount()。方法如下:

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

dwElapsed is now the number of elapsed milliseconds.

驻留的现在是经过的毫秒数。

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. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:

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

timeBeginPeriod(1);

at the beginning of your program or process and a:

在你的项目或过程的开始和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. 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.

最后,量子将变为1毫秒,您将在GetTickCount()调用中获得更好的时间分辨率。但是,这确实会对整个计算机的运行过程产生微妙的变化,所以请记住这一点。不过,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中我还不需要这么做。

#4


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;

}

Output: Timestamp: 20110912130940 // 2011 Sep 12 13:09:40

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

#5


3  

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;
 }

#6


2  

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);

#7


1  

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

还要注意clock()和usleep()之间的交互。usleep()暂停程序,时钟()只度量程序运行的时间。

If might be better off to use gettimeofday() as mentioned here

如果可以更好地使用gettimeofday(),就像这里提到的那样。

#8


0  

Use gettimeofday() or better clock_gettime()

使用gettimeofday()或better clock_gettime()

#9


0  

U can try routines in c time library (time.h). Plus take a look at the clock() in the same lib. 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.

您可以在c时间库(time.h)中尝试例程。另外,在同一个lib中查看时钟(),它给出了自prog启动以来时钟的滴答声。但是你可以在你想要集中精力的操作之前保存它的值,然后在那个操作之后再次捕获cliock滴答,然后找出两者之间的区别,从而得到时间差。

#1


29  

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

#2


8  

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.

类型的精度是实现定义的,即datetime的差异可能只返回完整的秒。

#3


6  

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(). Here's how:

在Windows中,使用GetTickCount()。方法如下:

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

dwElapsed is now the number of elapsed milliseconds.

驻留的现在是经过的毫秒数。

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. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:

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

timeBeginPeriod(1);

at the beginning of your program or process and a:

在你的项目或过程的开始和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. 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.

最后,量子将变为1毫秒,您将在GetTickCount()调用中获得更好的时间分辨率。但是,这确实会对整个计算机的运行过程产生微妙的变化,所以请记住这一点。不过,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中我还不需要这么做。

#4


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;

}

Output: Timestamp: 20110912130940 // 2011 Sep 12 13:09:40

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

#5


3  

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;
 }

#6


2  

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);

#7


1  

Also making aware of interactions between clock() and usleep(). usleep() suspends the program, and clock() only measures the time the program is running.

还要注意clock()和usleep()之间的交互。usleep()暂停程序,时钟()只度量程序运行的时间。

If might be better off to use gettimeofday() as mentioned here

如果可以更好地使用gettimeofday(),就像这里提到的那样。

#8


0  

Use gettimeofday() or better clock_gettime()

使用gettimeofday()或better clock_gettime()

#9


0  

U can try routines in c time library (time.h). Plus take a look at the clock() in the same lib. 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.

您可以在c时间库(time.h)中尝试例程。另外,在同一个lib中查看时钟(),它给出了自prog启动以来时钟的滴答声。但是你可以在你想要集中精力的操作之前保存它的值,然后在那个操作之后再次捕获cliock滴答,然后找出两者之间的区别,从而得到时间差。