这是代码,我想测量。我会喜欢一些帮助,我是编码的新手。我想看看可以随机选择的两个函数之间执行时间的差异。
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int complex_func ( int in)
{
int tmp1 ,i;
float tmp2 , tmp3 ;
for (i =0; i < 4112; i ++)
{
tmp1 = in*in*i;
tmp2 = (in+i )*( in+i )*( in+i);
tmp3 = tmp2 / tmp1 ;
}
return tmp3 ;
}
int simple_func ( int in)
{
int i,j=in;
for (i =0; i < 921; i ++) j = j+i;
return j;
}
main ( int argc , char ** argv )
{
int i,j;
time_t sec;
for (i = 0; i < 350000; i ++)
if ((j = rand ()) >0x3fffffff )
complex_func (j);
else simple_func (j);
}
提前致谢!
答案 0 :(得分:0)
有关基本指标,请参阅Execution time of C program
您可以使用以下内容将其应用于您的代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
double complex_time = 0.0;
double simple_time = 0.0;
int complex_func ( int in)
{
clock_t begin = clock(); // Start the watch
int tmp1 ,i;
float tmp2 , tmp3 ;
for (i =0; i < 4112; i ++)
{
tmp1 = in*in*i;
tmp2 = (in+i )*( in+i )*( in+i);
tmp3 = tmp2 / tmp1 ;
}
clock_t end = clock(); // Stop the watch
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; // Calculate elapsed time
complex_time += time_spent; // Add to global
return tmp3 ;
}
int simple_func ( int in)
{
clock_t begin = clock();
int i,j=in;
for (i =0; i < 921; i ++) j = j+i;
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
simple_time += time_spent;
return j;
}
main ( int argc , char ** argv )
{
int i,j;
for (i = 0; i < 350000; i ++)
if ((j = rand ()) >0x3fffffff )
complex_func (j);
else simple_func (j);
printf("complex=%f\n", complex_time); // Print result
printf("simple=%f\n", simple_time);
}
BTW:处理int
溢出,因为它未定义