在 C 中将一定数量的字符打印到标准输出的最快方法 [英] Fastest way to print a certain number of characters to stdout in C

查看:65
本文介绍了在 C 中将一定数量的字符打印到标准输出的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须向标准输出打印一定数量的空格,但这个数字不是固定的.我正在使用 putchar(),但我不确定这是否很快.在 C 中将一定数量的字符打印到标准输出的最快方法是什么?另外,我无法使用系统功能.

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.

感谢您的帮助!

推荐答案

我只想使用 fwrite.简单的.正确的.很简单.

I would just use fwrite. Simple. Correct. Easy.

void put_spaces(int n)
{
    static const char SPACES[32] = "                                ";
    for (; n >= 32; n -= 32)
        fwrite(SPACES, 32, 1, stdout);
    if (n)
        fwrite(SPACES, n, 1, stdout);
}

但是请注意,naive 版本也非常快:

Note, however, that the naive version is also quite fast:

void put_spaces(int n)
{
    while (n--)
        putchar(' ');
}

为什么这么快?在大多数系统上,putchar 是一个宏,大部分时间直接写入缓冲区.如果您不确定它是否快,正确的答案是分析您的应用程序,而不是先优化".

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".

远离malloc(这是不必要的),puts(每次调用时都会添加一个'\n'),和 printf(对于这么简单的任务来说太复杂了).

Stay away from malloc (it's just unnecessary), puts (which adds a '\n' every time you call it), and printf (it's too complicated for such a simple task).

这篇关于在 C 中将一定数量的字符打印到标准输出的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆