gpt4 book ai didi

c - 我希望能够测量这两个函数的执行时间,但无法理解它

转载 作者:行者123 更新时间:2023-11-30 20:33:54 25 4
gpt4 key购买 nike

这是代码,我想测量。我希望得到一些帮助,我是编码新手。我想看看两个可以随机选择的函数之间的执行时间差异。

#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);
}

提前致谢!

最佳答案

有关基本措施,请参阅 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);
}

顺便说一句:请注意 int 溢出,因为它未定义

关于c - 我希望能够测量这两个函数的执行时间,但无法理解它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43788892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com