一、windows 下
#include <time.h>
time_t start, end;
time(&start);
...
time(&end);
cout<<end - start;
#include <time.h>
void yourfunction()
{
clock_t start_1;//计时器开始。
clock_t finish_1;//计时器结束。
double duration_1;//经过时间。
start_1=clock();//计时开始。
。。。。。。
//记时结束。
finish_1=clock();
duration_1=(double)(finish_1-start_1)/CLOCKS_PER_SEC;
printf("/n循环用时:%.2f 秒/n",duration_1);
}
//下面可以获取微妙级时间
#include <windows.h>
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
//这是LARGE_INTEGER结构的定义,不需要定义
// typedef union _LARCE_INTEGER
// {
// struct
// {
// DWORD LowPart;// 4字节整型数
// LONG HighPart;// 4字节整型数
// };
// _int64 QuadPart;//8字节整型数
// }LARGE_INTEGER;
//
//实际程序
int main()
{
LARGE_INTEGER litmp;
_int64 QPart1,QPart2;//记录程序开始和结束的时间
double dfMinus, dfFreq, dfTim;//
QueryPerformanceFrequency(&litmp);//获得计数器的时钟频率
dfFreq=(double)litmp.QuadPart;
QueryPerformanceCounter(&litmp);
//获得初始值
QPart1=litmp.QuadPart;
/************************************************************************/
/* 要测试的程序 */
for (int i = 0 ; i< pow(10,5) ; ++i)
{
}
/************************************************************************/
QueryPerformanceCounter(&litmp);
//获得中止值
QPart2=litmp.QuadPart;
dfMinus=(double)(QPart2 - QPart1);
//获得对应的时间值
dfTim=dfMinus/dfFreq;
cout<<setprecision(20);
cout<<setiosflags(ios::fixed);
// cout<<setiosflags(ios::scientific);
cout<<"dfTim=dfMinus/dfFreq="<<dfTim<<endl;//结果以秒为单位
return 0;
}
二、linux 系统下
/*
#include <sys/time.h>
int gettimeofday(struct timeval *tv,struct timezone *tz);
strut timeval
{
long tv_sec; ///* 秒数
long tv_usec; ///* 微秒数
};
//gettimeofday将时间保存在结构tv之中.tz一般我们使用NULL来代替.
*/
#include <sys/time.h>
#include <stdio.h>
#include <math.h>
void function()
{
unsigned int i,j;
double y;
for(i=0;i<1000;i++)
for(j=0;j<1000;j++)
y=sin((double)i);
}
int main()
{
struct timeval tstart,tend;
float timeuse;
gettimeofday(&tstart,NULL);
function();
gettimeofday(&tend,NULL);
timeuse=1000000*(tend.tv_sec-tstart.tv_sec) + tend.tv_usec - tstart.tv_usec;
timeuse/=1000000;
printf("Used Time:%.16fs",timeuse);
return 0;
}
//#gcc -o testGetTime gettimeofday.c -lm
//# time testGetTime