我是一名初级 C 程序员,我读到 printf()
是非常复杂的函数,速度非常慢并且消耗许多 CPU 周期。所以我想知道标准纯 c 库中是否存在任何比 printf() 更快的函数,以及何时使用该函数以及何时不使用它。我的目标是编写可以在任何计算机和/或嵌入式系统上运行的高效代码
最佳答案
实际上我发现 write()
是 printf()
最快的替代方案
我编写了 2 个小程序,将 hello world 打印到标准输出
第一个
#include <stdio.h>
#include <string.h>
#include <unistd.h> int main() {
char* h = "hello world\n";
for ( int i=0; i < 100000; i++) write(0,h,strlen(h));
}
还有第二个
#include <stdio.h>
int main() {
char* x = "hello world\n";
for (int i =0;i<100000; i++) printf("%s",x); }
并比较了这两个程序在我的电脑上的运行时间 第一个在 2.740 秒内终止 而第二个在 3.071 秒内终止
关于c - 比 printf 更快的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27942929/