我一直在 WSL 和 Windows 上使用下面的代码。使用 MSVC 编译后,代码在 Windows 上按预期工作。在 WSL2(Ubuntu) 上,使用 GCC 编译后我得到了意想不到的结果。
该代码生成 2 个随机整数并打印它们,然后在程序退出前等待 5 秒。但是在 bash 上,打印只发生在 5 秒之后,而不是之前。
请看下面的代码。
谢谢
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
clock_t start_time = clock();
srand(time(NULL));
for(unsigned int i = 0; i < 2; i++)
printf("%u ", rand() % 10); // <--- Prints after 5 seconds on WSL 2 (Ubuntu)
while(clock() - start_time < CLOCKS_PER_SEC * 5);
return 0;
}