再很多的竞赛代码中,为了加快C++的输入,经常为加入以下代码
std::ios::sync_with_stdio(false);
std::cin.tie(0);
第一句取消stdin和cin的同步,可以加快cin的速度
第二句取消了cin 于 cout的绑定,默认情况下,cin的时候会让cout的缓冲flush。
但是经过我在VS2019的测试发现这两句优化代码,并没有太大作用,而且cin 似乎比scanf要快。
以下是测试代码:
C语言写文件:
int writeFileC() {
FILE* f = fopen("data.txt", "w");
for (int i = 0; i < 100000000; ++i) {
fprintf(f, "%d", rand());
}
return 0;
}
C语言读文件:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int readFileC() {
int start = clock();
FILE* f = freopen("data.txt", "r", stdin);
for (int i = 0; i < 100000000; ++i) {
int t;
scanf("%d", &t);
}
printf("%.3lf\n", double(clock() - start) / CLOCKS_PER_SEC);
return 0;
}
C++读文件:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int readFileCPP() {
int start = clock();
FILE* f = freopen("data.txt", "r", stdin);
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
for (int i = 0; i < 100000000; ++i) {
int t;
std::cin >> t;
}
printf("%.3lf\n", double(clock() - start) / CLOCKS_PER_SEC);
return 0;
}