c - printf() 的时间复杂度?

标签 c time printf big-o complexity-theory

我想确定 printf 的时间复杂度,例如:

{
    printf("%d",
           i);
}

或者:
{
    printf("%c",
           array[i]);
}

假设 printf 的时间复杂度总是 O(1) 是否正确?

[编辑] 让我们使用一个交换两个值的函数:
void swap(...)

{

      tmp = x;
      x = y;    
      y = tmp;  

}

每个赋值表达式的成本为 1(就时间复杂度而言),因此 T(n) = 1 + 1 + 1 = 3 这意味着 O(1)。但是我能对这个功能说些什么呢?
void swap(...)

{

      tmp = x;
      x = y;    
      y = tmp;  

      printf("Value of x: %d", x);
      printf("Value of y: %d", y);

}

我可以说在这种情况下 T(n) 仍然是 O(1) 吗?

最佳答案

我认为这不是一个明智的问题,因为 printf的行为主要是实现定义的。 C 不会对系统在命中 printf 后决定执行的操作施加任何限制。 .它确实有一个流的概念。 C11 标准的第 7.21 节规定 printf作用于流。

在将流写入 (7.21.2.2) 之后,C 允许实现对流执行任何它想要的操作:

Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one- to-one correspondence between the characters in a stream and those in the external representation



所以您调用printf允许在 char 时写出 1 TB打印,并且每当 int 时打印 1 个字节被打印。

该标准甚至不要求写入发生在 printf 时。实际上被称为(7.21.3.3):

When a stream is unbuffered, characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters may be accumulated and transmitted to or from the host environment as a block. When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled... Support for these characteristics is implementation-defined.



the standard doesn't specify whether stdout is buffered or unbuffered .所以 C 允许 printf一旦你要求它写,几乎可以做任何感觉。

关于c - printf() 的时间复杂度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25828018/

相关文章:

c++ - printf 比 std::cout 快 5 倍以上?

c - 向下舍入浮点结果

c - 在 C 中打印所有列表元素

c - 是否可以在 Windows 上将 go-dll 加载到 c-dll 中?

go - 如何在 Go 中解析日历周数

c - 带有左对齐标志的 printf() 位置参数

macos - find 缺少选项 -printf,现在怎么办?

c - 获取网络中设备的 IP 地址

macos - 如何加速/减慢应用程序的 'time'

c - 如何在c中获得一周的第一天