Search code examples
ctiming

Is there a timing difference between defining time_t at first in function or after other declarations/definitions?


Lets assume this is my log function:

int log(const char *fmt, ...) {
    time_t now = time(NULL);
    int i;
    char buffer[1024];

    i = 0;
    /* code here */
}

vs

int log(const char *fmt, ...) {
    int i;
    char buffer[1024];
    time_t now;
    
    now = time(NULL);
    i = 0;
    
    /* code here */
}

I want to know if the first case is important to get the exact time for the log line. Or is it not that much relevant.

How much time does the program need to allocate 1024 bytes on the stack? (Is there a way to analyse that by gcc or do I have to use clock() calls?)

And what about time critical software?

I think the second part has better readablity. Any minds?


Solution

  • Stack allocation is performed upon entering the function scope, and it is very cheap, typically a single instruction subtracting the allocated space from the stack pointer, if any code at all. Calling time(NULL) before or after this will have no measurable impact, especially given the limited precision of the time() function which returns a number of seconds as an integer.

    The second approach is more readable and seems preferable.