1

My C program needs to evaluate time elapsed between sending/receiving a message from client to server. In order to debug, I used some printf() statements and they seem to slow down the program.

After removing all of them, the pattern of time becomes as expected. I wonder if there is any way to print that has little influence on execution time.

Chad
  • 1,750
  • 2
  • 16
  • 32
intteng
  • 33
  • 4
  • 2
    Is it any faster if you redirect output to a file? – dbush Feb 02 '23 at 20:15
  • 5
    If there aren't too many time points, you could just store them internally in the program and print them out after the program has left the time critical sections. – Ted Lyngmo Feb 02 '23 at 20:17
  • 2
    Note that in practice it's not the output that slows things down so much as your terminal displaying the output. As dbush says, try redirecting the output. – tadman Feb 02 '23 at 20:29
  • See my answer: [Need test to determine if asynchronous I/O is actually happening in C code](https://stackoverflow.com/a/65099395/5382650). It defines a ring queue of "event" structs that have identifiers and timestamps. It's a limited version of code I've used in production/realtime code to have "low impact" tracing [similar to `dtrace`] – Craig Estey Feb 02 '23 at 20:34
  • 2
    Ultimately, your program is doing extra work printing the debug information; extra work takes extra time. You could try moving the logging to a different thread that doesn't have the time constraints, but even that's fraught, and there has to be mechanism for getting the data to the logging thread, and the logging thread might end up holding up the active thread. You should separate debugging from timing if you possibly can! If you need timing, don't do the debugging printing; if you need the debug printing, don't do the timing. (Even timing is extra work!) – Jonathan Leffler Feb 02 '23 at 20:34
  • 1
    What is the debugging info? Do you want to copy the messages in & out to the debug log? Perhaps do some formatting? Perhaps do some numerical conversions? It's unclear what your debugging might entail... – Fe2O3 Feb 02 '23 at 20:35
  • Use gdb with hardware watchpoins a – 0___________ Feb 02 '23 at 21:50

1 Answers1

2

I would try to store the timestamps you need as a variable during the workflow, then print after the time-sensitive workflow is complete. This way you still have the information you need but shouldn't be impacting performance.

  • Here's a naive implementation of such a mechanism: [demo](https://godbolt.org/z/r496xTb6f). See [@Craig Estey's variant](https://stackoverflow.com/a/65099395/7582247) for a more fullblown solution. – Ted Lyngmo Feb 02 '23 at 21:02