求助:手贱试了一下printf的速度,结果比cout还慢
  • 板块学术版
  • 楼主chenhaoyang2008
  • 当前回复5
  • 已保存回复5
  • 发布时间2024/10/26 11:50
  • 上次更新2024/10/26 13:01:26
查看原帖
求助:手贱试了一下printf的速度,结果比cout还慢
1245705
chenhaoyang2008楼主2024/10/26 11:50

如题

编译器版本

PS C:\Users\ChenH> g++ --version
g++.exe (Rev1, Built by MSYS2 project) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

编译选项:-O2 -std=c++14


printf:

#include<bits/stdc++.h>

int a[10000000];

int main(){
	freopen("1.txt","w",stdout);
    srand(time(0));
    for(int i=0;i<10000000;i++){
        a[i]=rand();
    }
    for(int i=1;i<10000000;i++){
        printf("%d",a[i]);
    }
}

resualt:

--------------------------------
Process exited after 4.187 seconds with return value 0
请按任意键继续. . .

cout:

#include<bits/stdc++.h>

int a[10000000];

int main(){
	//std::ios::sync_with_stdio(0);
	freopen("1.txt","w",stdout);
    srand(time(0));
    for(int i=0;i<10000000;i++){
        a[i]=rand();
    }
    for(int i=1;i<10000000;i++){
        std::cout<<a[i];
    }
}

resualt(不关同步):

--------------------------------
Process exited after 2.667 seconds with return value 0
请按任意键继续. . .

关同步:

--------------------------------
Process exited after 1.162 seconds with return value 0
请按任意键继续. . .

求助:手贱试了一下printf的速度,结果比cout不关同步还慢,为什么,考场上到底该用哪个?

2024/10/26 11:50
加载中...