-2

This is the code and I want to measure. I would love some help, I'm new to coding. I want to see the difference in execution time between the two functions that can be randomly selected.

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

Thanks in advance!

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • Check `RAND_MAX` – BLUEPIXY May 04 '17 at 17:15
  • you want execution time for each loop of 350000? If that is the case, that is a lot of output. You need to specify exactly what you want to measure. And also you have return values from functions that you are not capturing in main(). – Nguai al May 04 '17 at 17:16
  • Given that `complex_func()` always exhibits undefined behavior, the performance doesn't matter. – EOF May 04 '17 at 17:27
  • 1
    Possible duplicate of [Execution time of C program](http://stackoverflow.com/questions/5248915/execution-time-of-c-program) – Support Ukraine May 04 '17 at 17:30

1 Answers1

0

For the basic measure see Execution time of C program

You can apply it to your code with something like:

#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: Take care of int overflow as it is undefined

Community
  • 1
  • 1
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63