怎样计算程序的执行时间(C语言中)?

用库函数或自己怎样写都可以。

在c语言中有专门处理系统时间,程序计时等等功能的库,
即time.h
在time.h中函数clock_t clock( void )可以完成计时功能。

这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。其中clock_t是用来保存时间的数据类型,在time.h文件中,我们可以找到对它的定义:
#ifndef _CLOCK_T_DEFINED
typedef long clock_t;
#define _CLOCK_T_DEFINED
#endif

很明显,clock_t是一个长整形数。在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,其定义如下:

#define CLOCKS_PER_SEC ((clock_t)1000)

可以看到每过千分之一秒(1毫秒),调用clock()函数返回的值就加1。

下面这个程序计算了循环1千万次所用的时间:

#include “stdio.h”
#include “stdlib.h”
#include “time.h”

int main( void )
{
long i = 10000000L;
clock_t start, finish;
double duration;
/* 测量一个事件持续的时间*/
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- ) ;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%f seconds\n", duration );
system("pause");
}

运行结果如下:

Time to do 10000000 empty loops is 0.03000 seconds

参考资料:http://www.zxbc.cn/html/cjjhs/0312542045823.html
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-06-29
gettime可以得到毫秒级的时间
#include <stdio.h>
#include <dos.h>

int main(void)
{
struct time t;

gettime(&t);
printf("The current time is: %2d:%02d:%02d.%02d\n",
t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);
return 0;
}本回答被网友采纳
相似回答