c/c++在windows下获取时间和计算时间差的几种方法总结

本文介绍了使用C++进行时间精度测量的方法,包括如何利用clock_t实现毫秒级计时及通过Windows API获取微秒级别的高精度时间差。适用于需要对程序运行效率进行评估和优化的场景。

website: http://blog.youkuaiyun.com/coder_xia/article/details/6566708

#include <time.h>

 clock_t start,ends;

 start=clock();

 //system("pause");

 ends=clock();
 cout<<ends-start<<endl;

 time_t 获得时间只能精确到,clock_t 获得时间能够精确到毫秒

// 下面可以获得微秒级别的时间差。

#include <Windows.h>
#include <stdio.h>

int main()
{
  LARGE_INTEGER start;
  LARGE_INTEGER end ;
  LARGE_INTEGER frequency;

  int i = 0;

  if (!QueryPerformanceFrequency(&frequency))
  {
  return -1;
  }

  QueryPerformanceCounter(&start); //开始计时

  for ( i = 0; i < 100000; ++i)
  {
  ;// 用循环来测试计时
  }

  QueryPerformanceCounter(&end); //结束计时

  printf("main cost:%f/n", (double)(end.QuadPart - start.QuadPart) / (double)frequency.QuadPart); //打印for循环执行时间

  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值