Nested C Functions

Hello, can someone tell me why the following code :

package main
/*
long Add ( long a, long b ) {

    return a + b ;

}

long caller2 ( long a, long b ) {

    return Add(a,b);

}

long caller (  ) {

    long numAdd = 1 ;
    long i ;
    for ( i = 1 ; i <= 10000000000 ; i++ ) {

        numAdd = caller2 ( numAdd, i ) ;

    }
    
    return numAdd ;

}
*/
import "C"
import ( "fmt"; "time" )
func main (  ) {

    var timeBefore = time.Now ( ) ;
    ///////////////////////////////
    var checkNumber C.long = C.caller( ) ;
    //////////////////////////////
    var timeAfter = time.Now ( ) ;
    fmt.Println ( checkNumber ) ;
    fmt.Println ( timeAfter.Sub(timeBefore) ) ;

}

Is so mush slower than :

package main
/*
long caller (  ) {


    long Add ( long a, long b ) { // nested function

        return a + b ;

    }


    long caller2 ( long a, long b ) { // nested function

        return Add(a,b);

    }


    long numAdd = 1 ;
    long i ;
    for ( i = 1 ; i <= 10000000000 ; i++ ) {

        numAdd = caller2 ( numAdd, i ) ;

    }
    
    return numAdd ;

}
*/
import "C"
import ( "fmt"; "time" )
func main (  ) {

    var timeBefore = time.Now ( ) ;
    ///////////////////////////////
    var checkNumber C.long = C.caller( ) ;
    //////////////////////////////
    var timeAfter = time.Now ( ) ;
    fmt.Println ( checkNumber ) ;
    fmt.Println ( timeAfter.Sub(timeBefore) ) ;

}

Result :

The first : 32.184687445s
The second : 6.873829046s

Does nested C functions case a little overhead compared to top-level functions?

It’s going to be down to the code generated by the C compiler. It wouldn’t surprise me if the results would vary between GCC and Clang (and other C compilers).

You’re likely to get better answers in a C forum than here. With pure C source of course.

1 Like