计算时间差,标准C提供了difftime函数,它的原型:double difftime( time_t timer1,time_t timer0);下面的这段代码编译没问题
#include <time.h>
int _tmain(int argc, _TCHAR* argv[])
{
time_t* start, *finish;
start=NULL;
finish=NULL;
long loop;
double result, elapsed_time;
printf( "Multiplying 2 floating point numbers 500 million times...\n" );
time( start );
start=&temp1;
for( loop = 0; loop < 500000000; loop++ )
result = 3.63 * 5.27;
time( finish);
elapsed_time = difftime( *finish, *start );
printf( "\nProgram takes %lf seconds.\n", elapsed_time );
return 0;
}
运行却有异常,linux直接core dump。通过调试跟踪,发现在使用了指针start和finish都是null;
time函数的形参是time_t *timer,但是在这里却不能是指针,为了使程序运行,我们可以使用下面的代码
#include <time.h>
int _tmain(int argc, _TCHAR* argv[])
{
time_t* start, *finish;
time_t temp1;
time_t temp2;
start=NULL;
finish=NULL;
long loop;
double result, elapsed_time;
printf( "Multiplying 2 floating point numbers 500 million times...\n" );
time( &temp1 );
start=&temp1;
for( loop = 0; loop < 500000000; loop++ )
result = 3.63 * 5.27;
time( &temp1+sizeof(time_t) );
finish=&temp1+sizeof(time_t);
elapsed_time = difftime( *finish, *start );
printf( "\nProgram takes %6.0f seconds.\n", elapsed_time );
return 0;
}
也可以在用temp2来替代&temp1+sizeof(time_t)