【黑科技】C++输入输出优化技巧
来源:互联网 发布:promise js 阮一峰 编辑:程序博客网 时间:2024/06/09 20:45
今天下午经过试验(GUOAK,EGG,TYX,WEATAO等人围观),得出以下输入输出优化结论;
对于一个有10000000个随机数字,大小约为38M的文本文件;
输入测试:
1、用scanf()方式读入需要5.01秒
2、用以下方式读入则只需要1.139秒
#include<iostream>#include<cstdio>using namespace std;void read(int &x){x=0;char c=getchar();while(c<'0' || c>'9')c=getchar();while(c>='0' && c<='9'){x=x*10+c-'0';c=getchar();} }int main(){freopen("tt.in","r",stdin);int i,j,k,m,n;for(i=1;i<=10000000;i++)read(n);//for(i=1;i<=10000000;i++)scanf("%d",&n);return 0;}输出测试:
对于上述文件
1、以printf()方式输出需要18.121秒
2、用以下方式输出则需要1.288秒
#include<iostream>#include<cstdio>using namespace std;void read(int &x){x=0;char c=getchar();while(c<'0' || c>'9')c=getchar();while(c>='0' && c<='9'){x=x*10+c-'0';c=getchar();} }void write(int x){if(x==0){putchar(48);return;}int len=0,dg[20];while(x>0){dg[++len]=x%10;x/=10;}for(int i=len;i>=1;i--)putchar(dg[i]+48);}int main(){freopen("tt.in","r",stdin);freopen("tt.out","w",stdout);int i,j,k,m,n;//for(i=1;i<=10000000;i++){read(n);printf("%d ",n);}for(i=1;i<=10000000;i++){read(n);write(n);putchar(' ');}return 0;}关于输出优化,罗大神又有了不用开数组的方法:
void write(int x){int y=10,len=1;while(y<=x){y*=10;len++;}while(len--){y/=10;putchar(x/y+48);x%=y;}}
9 0
- 【黑科技】C++输入输出优化技巧
- 【黑科技】C++输入输出优化技巧
- 【考试技巧】输入输出优化
- 各种有用的东西、黑科技、技巧
- 各种有用的东西、黑科技、技巧
- 转载-css动画优化黑科技
- C/C++:scanf函数的黑科技
- C++——include<黑科技>
- c语言输入输出优化
- 黑科技
- 黑科技
- 黑科技
- 《黑科技》
- (持续更新)一些黑科技和技巧
- 读入输出优化 黑科技 快过fread&&fwite
- 黑帽SEO优化技巧大揭秘
- 黑科技 —— Type-C 接口与 USB3.1
- 【编程技巧】——输入输出优化
- 写的超级棒
- UVa 1395
- 返回一级指针 创建链表
- 制作html网页时如何使用CSS使背景图片拉伸(填充)
- hdoj5976Harmonic Value Description
- 【黑科技】C++输入输出优化技巧
- 内部类
- 什么是OAuth 2.0
- Genymotion创建模拟器的正确姿势
- PHP与MYSQL事务处理
- MySQL学习笔记6:运算符和函数
- Sql Server 2016 新功能——内置的 Temporal Tables
- Struts2文件上传与下载中的中文乱码问题解决方案
- ViewPager的setOnPageChangeListener方法详解