gpt4 book ai didi

c - 为什么第一个 printf 需要更长的时间?

转载 作者:太空狗 更新时间:2023-10-29 15:43:53 24 4
gpt4 key购买 nike

我在玩高精度计时器,我的第一个测试是使用 rdtsc 来测量 printf。下面是我的测试 prpgram 及其输出。我注意到的是,第一次运行 printf 时,第一次打印花费的时间始终比后续打印花费的时间长 25 倍。这是为什么?

#include <stdio.h>
#include <stdint.h>

// Sample code grabbed from wikipedia
__inline__ uint64_t rdtsc(void)
{
uint32_t lo, hi;
__asm__ __volatile__ (
"xorl %%eax,%%eax \n cpuid"
::: "%rax", "%rbx", "%rcx", "%rdx");
__asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
return (uint64_t)hi << 32 | lo;
}

int main(int argc, const char *argv[])
{
unsigned int i;
uint64_t counter[10];
uint64_t sum = 0;
for (i = 0; i < 10; i++)
{
counter[i] = rdtsc();
printf("Hello, world\n");
counter[i] = rdtsc() - counter[i];
}

for (i = 0; i < 10; i++)
{
printf("counter[%d] = %lld\n", i, counter[i]);
sum += counter[i];
}
printf("avg = %lld\n", sum/10);
return 0;
}

输出:

Hello, world
Hello, world
Hello, world
Hello, world
Hello, world
Hello, world
Hello, world
Hello, world
Hello, world
Hello, world
counter[0] = 108165
counter[1] = 6375
counter[2] = 4388
counter[3] = 4388
counter[4] = 4380
counter[5] = 4545
counter[6] = 4215
counter[7] = 4290
counter[8] = 4237
counter[9] = 4320
avg = 14930

(作为引用,这是在 OSX 上用 gcc 编译的)

最佳答案

我的猜测是,在第一次调用 printf 时,stdout 资源不在缓存中,调用需要将其放入缓存 - 因此速度较慢。对于所有后续调用,缓存已经是热的。

第二种可能的解释是,如果这是在 Linux 上(也可能适用于 OSX,我不确定),程序需要设置流方向。 (ASCII 与 UNICODE)这是在第一次调用使用该流的函数时完成的,并且在流关闭之前是静态的。我不知道设置这个方向的开销是多少,但这是一次性成本。

如果有人认为我完全错了,请随时纠正我。

关于c - 为什么第一个 printf 需要更长的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7284951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com