我想确定 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/