我希望能够测量这 2 个函数的执行时间,但无法全神贯注

I want to be able to measure the time of execution of this 2 functions but can't wrap my head around it

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

#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 溢出,因为它是未定义的