在 C 中将一定数量的字符打印到 stdout 的最快方法
我必须将一定数量的空格打印到标准输出,但这个数量不是固定的。我正在使用 putchar(),但我不确定这是否很快。在 C 中将一定数量的字符打印到 stdout 的最快方法是什么?另外,我无法使用系统功能。
谢谢你的帮助!
I have to print a certain number of blank spaces to stdout, but this number is not fixed. I'm using putchar(), but I'm not sure if this is fast. What is the fastest way to print a certain number of characters to stdout in C? Also, I cannot use system functions.
Thanks for you help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我只会使用
fwrite
。简单的。正确的。简单的。但请注意,天真的版本也相当快:
为什么它这么快?在大多数系统上,
putchar
是一个在大多数情况下直接写入缓冲区的宏。如果您不确定它是否快,正确的答案是分析您的应用程序,而不是“首先优化”。远离
malloc
(它只是不必要的)、puts
(每次调用时都会添加'\n'
)和>printf
(对于这样一个简单的任务来说太复杂了)。I would just use
fwrite
. Simple. Correct. Easy.Note, however, that the naive version is also quite fast:
Why is it fast? On most systems,
putchar
is a macro which writes directly into a buffer most of the time. If you're not sure it's fast, the correct answer is profile your application, not "optimize first".Stay away from
malloc
(it's just unnecessary),puts
(which adds a'\n'
every time you call it), andprintf
(it's too complicated for such a simple task).我会尝试使用系统命令而不是自己制作。
像这样的东西:
就可以了。
I would try to use the system commands instead of making my own.
something like:
would do the trick.
printf()
允许您调整要打印的空格数,但这必须在格式字符串中说明。请参阅此处作为参考。printf()
allows you to adjust the number of spaces to be print, but this has to be stated in the format string. Se here for reference.我假设“系统功能”是指非标准扩展。在这种情况下,这完全取决于您的意思是最快的写入速度还是最快的执行速度?
如果是前者,并假设有上限,您可以使用类似的东西:
如果是后者,这样的东西应该是一个很好的起点:
您需要知道函数调用可能是昂贵的,即使有输出缓冲。在这种情况下,最好调用一次 puts 来输出一百个字符,而不是调用 putchar 一百次。
I'm assuming by "system functions", you mean non-standard extensions. In which case, it all depends on whether you mean fastest to write or fastest to execute?
If the former, and assuming there's an upper limit, you can just use something like:
If the latter, something like this should be a good starting point:
You need to be aware that function calls can be expensive, even with output buffering. In that case, it may be best to call
puts
once to output a hundred characters rather than callputchar
a hundred times.也许:
Perhaps:
(如果空格数量不是特别多的话)
(If the number of spaces isn't outrageous)
我不懂c,但这是基本思想。
创建一个大小为 8192 的数组,并用空格完全填充该特定数组,现在您可以使用 put 或编写系统调用或使用高效的东西,然后打印该数组。
这里我有一个 go 代码片段,但如果你更喜欢 c,你可以看到 示例说明了如何做到这一点,它实际上是 GNU 的 yes 程序,它打印内容的速度非常快,那里有后续解释。
I don't known c, but here is the basic idea.
create an array of size 8192, and completely fill that particular array with spaces, now you can use puts or write system call or use something which is efficient, and then print this array.
Here I have a code snippet in go, but if you prefer c, you can see an example of how you do it, its actually GNU's yes program which is freaking fast at printing things, there is followed up explanation over there.