C语言怎样提取系统时间且将其用于求时间差运算

VC++6.0下,C语言怎样提取系统时间且将其用于求时间差运算

提供两种方法作为参考:第一种,使用系统函数GetSystemTime和结构体SYSTEMTIME#include <windows.h>SYSTEMTIME stbegin,stend在开始时间点运行 GetSystemTime(&stbegin); 在结束时间点运行 GetSystemTime(&stend); 这时获得起始时间和结束时间,可以进行时间差运算。typedef struct _SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds; } SYSTEMTIME,
*PSYSTEMTIME; 第二种,如果使用MFC或者ATL库,可以使用COleDateTime类COleDateTime stbegin,stend;开始时间:stbegin=COleDateTime.GetCurrentTime();结束时间:stend=COleDateTime.GetCurrentTime();时间差:COleDateTime stresult=stend-stend;再使用COleDateTime的format函数可以把值转换成一个字符串
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-03-28
如果是要求精确的话,用微秒来统计;在进入一段代码前把时间计下,然后在执行完一段代码后再去获取时间。两个时间 想减就是该段代码的执行时间,从面可以测出效率。下面附上一段代码:#include <iostream>
#include <time.h>
#include <sys/timeb.h>
#define START 1
#define STOP 0
#define BAIWANG 1000000
using namespace std;
int GetMilitime()
{
timeb t;
ftime(&t);
return 1000 * t.time + t.millitm;
}int Xiaoli(int type)
{
static long tt = GetMilitime();
if (type==STOP)
{
long old = tt;
tt = GetMilitime();
cout<<"运行时间为"<<tt-old<<"微秒"<<endl;
return tt - old;
}
return 0;
}
void main()
{
int i =0;
Xiaoli(START); //把要测试的代码放在Xiaoli(START) 与Xiaoli(STOP)之间
for (i=0;i<1000;i++)
{
for(int j =0;j<BAIWANG;j++);
}
Xiaoli(STOP);

}
第2个回答  2013-03-27
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
void my_subroutine(long n) {
// timing a subroutine call:
char s[16];
for (long i = 0; i < n; i++) {
_itoa(i, s, sizeof(s));
}
}
int main(int argc, char* argv[]) {
long n = 1000000;
clock_t start = clock(); //记录开始时间
my_subroutine(n); //调用函数,花费时间
clock_t finish = clock(); //结束时间
double duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf("Time for %d iterations: %lf s",n,duration);
return 0;
}本回答被网友采纳
第3个回答  2013-03-27
clock_t start = clock();

clock_t end = clock();

所用时间 = (end-start) * 1.0 /CLK_TCK 秒
相似回答