printf slows down my program

后端 未结 9 744
旧巷少年郎
旧巷少年郎 2020-12-14 01:55

I have a small C program to calculate hashes (for hash tables). The code looks quite clean I hope, but there\'s something unrelated to it that\'s bugging me.

I can e

相关标签:
9条回答
  • 2020-12-14 02:44
    1. Why not create the strings on demand rather that at the point of construction? There is no point in outputting 40 screens of data in one second how can you possibly read it? Why not create the output as required and just display the last screen full and then as required it the user scrolls???

    2. Why not use sprintf to print to a string and then build a concatenated string of all the results in memory and print at the end?

    3. By switching to sprintf you can clearly see how much time is spent in the format conversion and how much is spent displaying the result to the console and change the code appropriately.

    4. Console output is by definition slow, creating a hash is only manipulating a few bytes of memory. Console output needs to go through many layers of the operating system, which will have code to handle thread/process locking etc. once it eventually gets to the display driver which maybe a 9600 baud device! or large bitmap display, simple functions like scrolling the screen may involve manipulating megabytes of memory.

    0 讨论(0)
  • 2020-12-14 02:45

    I discovered long ago using this technique something that should have been obvious. Not only is I/O slow, especially to the console, but formatting decimal numbers is not fast either. If you can put the numbers in binary into big buffers, and write those to a file, you'll find it's a lot faster.

    Besides, who's going to read them? There's no point printing them all in a human-readable format if nobody needs to read all of them.

    0 讨论(0)
  • 2020-12-14 02:47

    You could store your strings in a buffer and output them to a file (or console) at the end or periodically, when your buffer is full.

    If outputting to a console, scrolling is usually a killer.

    0 讨论(0)
提交回复
热议问题