如何尽可能快地输出固定缓冲区?

Zib*_*bri 3 c unix linux macos fwrite

示例代码:

#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <pthread.h>

int
main (int argc, char **argv)
{

  unsigned char buffer[128];
  char buf[0x4000];
  setvbuf (stdout, buf, _IOFBF, 0x4000);
  fork ();
  fork ();

  pthread_t this_thread = pthread_self ();

  struct sched_param params;

  params.sched_priority = sched_get_priority_max (SCHED_RR);

  pthread_setschedparam (this_thread, SCHED_RR, &params);


  while (1)
    {
      fwrite (&buffer, 128, 1, stdout);
    }
}
Run Code Online (Sandbox Code Playgroud)

该程序打开 4 个线程,并在 stdout 上输出“buffer”的内容,该内容在 64 位 cpu 上为 128 字节或 16 个长整型。

如果我然后运行:

./写测试| pv -ptebaSs 800G >/dev/null

我得到的速度约为 7.5 GB/s。

顺便说一句,如果我这样做的话,这与我得到的速度是一样的:

$ mkfifo out
$ dd if=/dev/zero bs=16384 >out &
$ dd if=/dev/zero bs=16384 >out &
$ dd if=/dev/zero bs=16384 >out &
$ dd if=/dev/zero bs=16384 >out &
pv <out -ptebaSs 800G >/dev/null
Run Code Online (Sandbox Code Playgroud)

有什么办法可以让它更快吗?笔记。实际程序中的缓冲区未填充零。

我的好奇心是了解单个程序(多线程或多进程)可以输出多少数据

看来4个人都没听懂这个简单的问题。我什至把问题的原因加粗了。

Zib*_*bri 5

看来 Linux 调度程序和 IO 优先级在速度减慢中发挥了重要作用。

此外,Spectre 和其他 CPU 漏洞缓解措施也开始发挥作用。

经过进一步优化,为了达到更快的速度,我必须调整以下内容:

1) program nice level (nice -n -20)
2) program ionice level (ionice -c 1 -n 7)
3) pipe size increased 8 times.
4) disable cpu mitigations by adding "pti=off spectre_v2=off l1tf=off" in kernel command line
5) tuning the linux scheduler

echo -n -1 >/proc/sys/kernel/sched_rt_runtime_us
echo -n -1 >/proc/sys/kernel/sched_rt_period_us
echo -n -1 >/proc/sys/kernel/sched_rr_timeslice_ms
echo -n 0 >/proc/sys/kernel/sched_tunable_scaling
Run Code Online (Sandbox Code Playgroud)

现在程序输出(在同一台电脑上)8.00 GB/秒!

如果您有其他想法,欢迎贡献。