简体   繁体   中英

Function takes unusually long time to return

I am measuring how much time it takes to execute function compute_secret(). The pseudo code below is how I do my measurement. The problem is that, there is a quite large different in between total_inside (the time its take to execute the function body, measure inside the callee) vs. total_outside (measure inside the caller). For example, total_inside = 127ms , total_outside = 238ms .

I understand that it takes sometime to call and return from function call. But it should not takes "that" long.

So what are the common reasons when calling and returning from function cost too much time ?

int encrypt(args){
    time start_inside = get_current_time();
    /**
         actually compute stuff
     **/
    time end_inside = get_current_time();
    time total_inside = end_inside - start_inside;
}

int main(){
    time start_outside = get_current_time();

    encrypt(args);

    time end_outside = get_current_time();
    time total_outside = end_outside - start_outside;
}

From a glance at the psudo-code, I see a number of things:

  • the first is that it's pseudo-code, which rather hampers our ability to do a full analysis :-) So comments below are based on what I see as most likely options.

  • you haven't actually posted the code for get_current_time() , the execution time of that may be irrelevant but that's not necessarily the case. Sometimes timing functions get in the way of accuarte timing.

  • the reason I mention that last point is that the outer time calculation will consist of the function calculations itself, the stack setup and teardown, and the inner time calculation. You should probably just run with the outer time to see if the timings are reduced.

  • because of the vagaries of code execution, it's often better to time something in a loop and average the time taken. For all we know, the first call may take 250ms and subsequent calls take 1ms.

If you're really concerned about stack setup and teardown (it's usually not too bad but it's definitely not free and, for very short-lived functions, it can often swamp the execution time of the actual work being done), there are options.

For example, you can choose higher optimisation levels, or force your function inline such as by making it a function macro, assuming you protect against all the usual macro-related issues, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM