shamir shakir wrote:
> Hi
> Today I found a new (or probably) bad thing. I use to call fuction for
> anything I need. But It takes valuable time taking value and returning
> something.
>  :(
> 
> // This code describe how bad , calling fuction is...
> 
> #include <stdio.h>
> #include <time.h>
> 
> unsigned long int fuction(long long i)
> {
>     // Do something ...
> 
>     return i ;
> }
> 
> int main()
> {
>     unsigned long long i;
>     time_t end, start;
> 
> 
>     start  = clock() ;
>         for(int i=0; i<1000; i++)
>             for(int j=0; j<1000; j++)
>                 for(int k=0; k<1000; k++) ;
>     end = clock() ;
> 
>     printf("IN MAIN FUNCTION  ... \n ") ;
>     printf("\t Total clock : %u \n", end-start) ;
> 
> 
>     start = clock() ;
>         for(int i=0; i<1000; i++)
>             for(int j=0; j<1000; j++)
>                 for(int k=0; k<1000; k++)
>                     fuction(i) ;
>     end = clock() ;
> 
>     printf("IN SUB FUNCTION .... \n") ;
>     printf("\t Total clock : %u \n ", end-start ) ;
>     printf("\nFunctions take a lot of time :( " ) ;
> 
>     return 0 ;
> }
> 
> 
> Now , I just want to know is this a good practice to work and utilize
> function calling? Or I'm just gonna work with main?

This is a non-issue.  You are calling a function that _DOES NOTHING_ 1 
billion times.  In addition, in the first example, most compilers are 
going to see that the for-loops DO NOTHING and optimize them out from 
existence.

Plus, for small functions, most modern compilers support the 'inline' 
keyword and will inline the function wherever it is used.  A good, 
modern compiler with optimizations turned on should completely eliminate 
both sets of for-loops.

A function does have overhead, but VERY little.  On most systems, 
parameters are pushed onto the stack and then the previous execution 
pointer gets pushed onto the stack and then the function itself will 
usually push additional variables onto the stack.  On exit, the function 
will pop everything off the stack it added, the execution pointer will 
be moved back to where it came from and removed from the stack, and all 
variables used during the call are removed from the stack.

Functions, classes, and templates are there so you can organize your 
code into concise, logical units that are easy to maintain.  _IF_ there 
is a performance problem, use a code profiler to identify the slowest 
function calls.

-- 
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197

*NEW* MyTaskFocus 1.1
Get on task.  Stay on task.

http://www.CubicleSoft.com/MyTaskFocus/

Reply via email to