当前所在位置:珠峰网资料 >> 计算机 >> 计算机等级考试 >> 正文
VC获取高精度时间的例子
发布时间:2010/7/6 11:26:39 来源:城市学习网 编辑:ziteng
  #include <stdio.h>
  #include "KTimer.h"
  main()
  {
  unsigned t;
  KTimer timer;
  timer.Start();
  Sleep(1000);
  t = timer.Stop();
  printf("Lasting Time: %d\n",t);
  }
  //Timer2.cpp 使用了timeGetTime函数
  //需包含<mmsys.h>,但由于Windows头文件错综复杂的关系
  //简单包含<windows.h>比较偷懒:)
  //编译行:CL timer2.cpp /link winmm.lib
  #include <windows.h>
  #include <stdio.h>
  main()
  {
  DWORD t1, t2;
  t1 = timeGetTime();
  Sleep(1000);
  t2 = timeGetTime();
  printf("Begin Time: %u\n", t1);
  printf("End Time: %u\n", t2);
  printf("Lasting Time: %u\n",(t2-t1));
  } [NextPage]   //Timer3.cpp 使用了QueryPerformanceCounter函数
  //编译行:CL timer3.cpp /link KERNEl32.lib
  #include <windows.h>
  #include <stdio.h>
  main()
  {
  LARGE_INTEGER t1, t2, tc;
  QueryPerformanceFrequency(&tc);
  printf("Frequency: %u\n", tc.QuadPart);
  QueryPerformanceCounter(&t1);
  Sleep(1000);
  QueryPerformanceCounter(&t2);
  printf("Begin Time: %u\n", t1.QuadPart);
  printf("End Time: %u\n", t2.QuadPart);
  printf("Lasting Time: %u\n",( t2.QuadPart- t1.QuadPart));
  // 这里要计算时间(单位为秒),应加上这一句
  double dTotalTime = (double)(t2.QuadPart-t1.QuadPart) / (double)tc.QuadPart;    //秒
  printf("耗时: %f\n", dTotalTime);
  }
  //以上三个示例程序都是测试1秒钟休眠所耗费的时间
  file://测/试环境:Celeron 800MHz / 256M SDRAM
  // Windows 2000 Professional SP2
  // Microsoft Visual C++ 6.0 SP5
  ////////////////////////////////////////////////
  以下是Timer1的运行结果,使用的是高精度的RDTSC指令
  Lasting Time: 804586872
  以下是Timer2的运行结果,使用的是最粗糙的timeGetTime API
  Begin Time: 20254254
  End Time: 20255255
  Lasting Time: 1001
  以下是Timer3的运行结果,使用的是QueryPerformanceCount API
  Frequency: 3579545
  Begin Time: 3804729124
  End Time: 3808298836
  Lasting Time: 3569712
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved