ChefZ -- 磨劍錄 (A Coder's Log)

慣看秋月春風 一壺濁酒喜相逢 古今多少事 皆賦談笑中
posts - 42, comments - 3, trackbacks - 0, articles - 6

精準時間 + nanoSleep(...)

Posted on 2008-12-05 19:37 chefZ 阅读(224) 评论(0)  编辑 收藏 引用

int gettimeofday (struct timeval *tv, void* tz)
{
  union {
    __int64 ns100; /*time since 1 Jan 1601 in 100ns units */
    FILETIME ft;
  } now;


  GetSystemTimeAsFileTime (&now.ft);
  tv->tv_usec = (long) ((now.ns100 / 10L) % 1000000L);
  tv->tv_sec = (long) ((now.ns100 - 116444736000000000L) / 10000000L);
  return (0);
}

typedef  struct _BinInt32
{
    __int32 i32[2];
} BigInt32;

typedef  struct _BigInt64
{
    __int64 i64;
} BigInt64;

typedef union _bigInt
{
    BigInt32 int32val;
    BigInt64 int64val;
    LONGLONG dataBuf;
} BigInt;

unsigned int getRandomSeed(void)
{
BigInt timeCounter;

    QueryPerformanceCounter((LARGE_INTEGER*)&timeCounter);
    return((unsigned int)timeCounter.dataBuf);
}

void nanoSleepEx(int delay)
{
BigInt start_ticks, end_ticks, cpuFreq;
double dfFreq;
LONGLONG dfCount;

    QueryPerformanceFrequency((LARGE_INTEGER*)&cpuFreq);
    dfFreq = ((double)cpuFreq.dataBuf) / 1000000000L;
    dfCount = (LONGLONG)(((double)delay) * dfFreq);

    _asm
    {
        RDTSC
        mov start_ticks.int32val.i32[0], eax
        mov start_ticks.int32val.i32[4], edx
    }

    do
    {
        _asm
        {
            RDTSC
            mov end_ticks.int32val.i32[0], eax
            mov end_ticks.int32val.i32[4], edx
        }

    } while((end_ticks.dataBuf - start_ticks.dataBuf - dfCount) < 0);
}

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理