检索计时器的最有效方法?

时间:2011-09-18 11:30:48

标签: c++ time

我以前从未真正与计时器合作,但我现在的项目需要一个。

所以这可能是一个愚蠢的问题:但是为游戏检索计时器的“正常”方式是什么?是否有更好/更有效的方式?

由于

3 个答案:

答案 0 :(得分:1)

如果您需要跨平台且高性能的时间库,请使用boost::date_time。对于定时器,只需获取当前时间,并从下一个读数中减去它(它们具有用于计算时间差等的运算符,代码是可读的)。

使用boost::posix_time::microsecond_clock::universal_time()读取当前时间并存储在ptime结构中。 (posix_并不是指它仅在POSIX系统上可用;它仅表示它是在POSIX时间概念之后建模的。)

答案 1 :(得分:1)

由于您可能希望时间过去,而且可能很少,您可能需要使用clock()中定义的time.h函数。

这是我在MSDN Library中发现的:


计算调用过程使用的挂钟时间。

clock_t clock( void );

返回值

自进程开始以来经过的挂钟时间(以秒为单位的经过时间乘以CLOCKS_PER_SEC)。如果经过的时间不可用,则函数返回-1,转换为clock_t。

<强>说明

时钟函数告诉调用进程使用了​​多长时间。计时器滴答大约等于1 / CLOCKS_PER_SEC秒。在6.0之前的Microsoft C版本中,CLOCKS_PER_SEC常量称为CLK_TCK。

示例:     // crt_clock.c     //这个例子提示了多长时间     //程序要运行然后连续运行     //显示该时间段的已用时间。     //

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void sleep( clock_t wait );

int main( void )
{
   long    i = 6000000L;
   clock_t start, finish;
   double  duration;

   // Delay for a specified time.
   printf( "Delay for three seconds\n" );
   sleep( (clock_t)3 * CLOCKS_PER_SEC );
   printf( "Done!\n" );

   // Measure the duration of an event.
   printf( "Time to do %ld empty loops is ", i );
   start = clock();
   while( i-- ) 
      ;
   finish = clock();
   duration = (double)(finish - start) / CLOCKS_PER_SEC;
   printf( "%2.1f seconds\n", duration );
}

// Pauses for a specified number of milliseconds.
void sleep( clock_t wait )
{
   clock_t goal;
   goal = wait + clock();
   while( goal > clock() )
      ;
}

<强>输出

Delay for three seconds
Done!
Time to do 6000000 empty loops is 0.1 seconds

答案 2 :(得分:1)

如果您在Windows上使用C ++,则需要使用QueryPerformanceCounter / QueryPerformanceFrequency

http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(V = vs.85)的.aspx

如果你在linux上,请查看clock_gettime(CLOCK_REALTIME)

http://linux.die.net/man/3/clock_gettime

clock()建议不正确,因为它是在过程中使用的时间。因为有一个循环,他的函数最终会开始正确,但如果你阻止那么这将无效。

http://linux.die.net/man/3/clock