在 C 中将一定数量的字符打印到 stdout 的最快方法

发布于 2024-11-07 02:05:11 字数 126 浏览 0 评论 0原文

我必须将一定数量的空格打印到标准输出,但这个数量不是固定的。我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

献世佛 2024-11-14 02:05:11

我只会使用fwrite。简单的。正确的。简单的。

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);
}

但请注意,天真的版本也相当快:

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

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

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

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);
}

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

void put_spaces(int n)
{
    while (n--)
        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".

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

倾`听者〃 2024-11-14 02:05:11

我会尝试使用系统命令而不是自己制作。

像这样的东西:

void print_spaces(unsigned int number_of_spaces) {
  char* spaces = malloc(sizeof(char)*number_of_spaces + 1);
  memset (spaces,' ',number_of_spaces);
  spaces[number_of_spaces] = '\0';
  printf("%s",spaces);
  free(spaces);
}

就可以了。

I would try to use the system commands instead of making my own.

something like:

void print_spaces(unsigned int number_of_spaces) {
  char* spaces = malloc(sizeof(char)*number_of_spaces + 1);
  memset (spaces,' ',number_of_spaces);
  spaces[number_of_spaces] = '\0';
  printf("%s",spaces);
  free(spaces);
}

would do the trick.

能否归途做我良人 2024-11-14 02:05:11

printf() 允许您调整要打印的空格数,但这必须在格式字符串中说明。请参阅此处作为参考。

char format[256];
sprintf(format, "%%%ds", number_of_spaces); // creates the format string
printf(format, " ");

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.

char format[256];
sprintf(format, "%%%ds", number_of_spaces); // creates the format string
printf(format, " ");
梦忆晨望 2024-11-14 02:05:11

我假设“系统功能”是指非标准扩展。在这种情况下,这完全取决于您的意思是最快的写入速度还是最快的执行速度?

如果是前者,并假设有上限,您可以使用类似的东西:

void outSpaces (unsigned int num) {
    static char *lotsaSpaces = "                       ";
    printf ("%*.*s", num, num, lotsaSpaces);
}

如果是后者,这样的东西应该是一个很好的起点:

void outSpaces (unsigned int num) {
    static char *hundredSpaces = "<<insert 100 spaces here>>";
    while (num >= 100) {
        puts (hundredSpaces);
        num -= 100;
    }
    printf ("%*.*s", num, num, hundredSpaces);
}

您需要知道函数调用可能是昂贵的,即使有输出缓冲。在这种情况下,最好调用一次 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:

void outSpaces (unsigned int num) {
    static char *lotsaSpaces = "                       ";
    printf ("%*.*s", num, num, lotsaSpaces);
}

If the latter, something like this should be a good starting point:

void outSpaces (unsigned int num) {
    static char *hundredSpaces = "<<insert 100 spaces here>>";
    while (num >= 100) {
        puts (hundredSpaces);
        num -= 100;
    }
    printf ("%*.*s", num, num, hundredSpaces);
}

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 call putchar a hundred times.

遥远的她 2024-11-14 02:05:11

也许:

void PrintSpaces (int num_spaces)
{
  char *spaces = "                    "; /* twenty spaces */
  while (num_spaces > 20)
  {
    puts (spaces);
    num_spaces -= 20;
  }

  if (num_spaces)
  {
    puts (&spaces [19 - num_spaces]);
  }
}

Perhaps:

void PrintSpaces (int num_spaces)
{
  char *spaces = "                    "; /* twenty spaces */
  while (num_spaces > 20)
  {
    puts (spaces);
    num_spaces -= 20;
  }

  if (num_spaces)
  {
    puts (&spaces [19 - num_spaces]);
  }
}
撧情箌佬 2024-11-14 02:05:11
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

int main() {
    const size_t size = 5;
    char* const data = (char*)malloc(size * sizeof(char) + 1);
    if (!data) {
        return EXIT_FAILURE;
    }
    memset(data, ' ', size);
    data[size] = '\0'; // not needed (in this case)
    fwrite(data, sizeof(char), size, stdout);
    free(data);
    return EXIT_SUCCESS;
}

(如果空格数量不是特别多的话)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>

int main() {
    const size_t size = 5;
    char* const data = (char*)malloc(size * sizeof(char) + 1);
    if (!data) {
        return EXIT_FAILURE;
    }
    memset(data, ' ', size);
    data[size] = '\0'; // not needed (in this case)
    fwrite(data, sizeof(char), size, stdout);
    free(data);
    return EXIT_SUCCESS;
}

(If the number of spaces isn't outrageous)

给不了的爱 2024-11-14 02:05:11

我不懂c,但这是基本思想。
创建一个大小为 8192 的数组,并用空格完全填充该特定数组,现在您可以使用 put 或编写系统调用或使用高效的东西,然后打印该数组。
这里我有一个 go 代码片段,但如果你更喜欢 c,你可以看到 示例说明了如何做到这一点,它实际上是 GNU 的 yes 程序,它打印内容的速度非常快,那里有后续解释。

package main

import (
    "bufio"
    "os"
)

func main() {
    t := []byte{'y', '\n'}
    var used int
    const tot = 8192
    buf := make([]byte, 0, tot)

    for used < tot {
        buf = append(buf, t...)
        used += 2
    }

    //Filled complete array named as buf with "y\n"
    w := bufio.NewWriter(os.Stdout)
    for {
        w.Write(buf) //using write system call to print.
    }
    w.Flush()
}

//syscall.Write({without buf}) : 1.40MiB/s
//syscall.Write(buf) : 1.5GiB/s

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.

package main

import (
    "bufio"
    "os"
)

func main() {
    t := []byte{'y', '\n'}
    var used int
    const tot = 8192
    buf := make([]byte, 0, tot)

    for used < tot {
        buf = append(buf, t...)
        used += 2
    }

    //Filled complete array named as buf with "y\n"
    w := bufio.NewWriter(os.Stdout)
    for {
        w.Write(buf) //using write system call to print.
    }
    w.Flush()
}

//syscall.Write({without buf}) : 1.40MiB/s
//syscall.Write(buf) : 1.5GiB/s
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文