【问题标题】:What is most efficient way to read a file of integer in each line without opening it? [duplicate]在不打开每行中读取整数文件的最有效方法是什么? [复制]
【发布时间】:2015-05-09 03:39:00
【问题描述】:

什么是读取每行整数文件而不打开它的最有效方法? 我有一个每行只有整数的文件,即:num.txt

100
231 
312
...

在我的程序中,我使用while循环来读取它;

int input = 0;
while(cin >> input)
{        
// Assignment
}

我使用time a.out <num.txt 在 Linux 中阅读 事实证明,读取 1 亿 个数字大约需要 15 秒(用户时间)。所以我想知道有没有更好的方法来减少用户时间?

提前谢谢你!

【问题讨论】:

  • 如果您关心性能,请不要使用 iostream。
  • 只是为了避免在技术上误导自己,当您使用重定向“open(2) 和 read(2)
  • @tux3:我们已经多次证明 iostream 与其他读取文件的方法几乎相同。唯一有很大不同的是您是否可以将文件直接映射到内存中。 (如果您通过 stdin 输入它,最喜欢的方法将不起作用)-您可能必须打开 sync_with_stdio 才能获得合理的性能。
  • @qdii shauryachats 的回答非常棒,它简单且相当快。

标签: c++


【解决方案1】:
int input = 0;
ios_base::sync_with_stdio(false); 
//Add this statement and see the magic!
while(cin >> input)
{        
// Assignment
}

要使其超快(不推荐用于作业!),请使用getchar_unlocked()

int read_int() {
  char c = getchar_unlocked();
  while(c<'0' || c>'9') c = gc();
  int ret = 0;
  while(c>='0' && c<='9') {
    ret = 10 * ret + c - 48;
    c = getchar_unlocked();
  }
  return ret;
}

int input = 0;
while((input = read_int()) != EOF)
{        
// Assignment
}

Vaughn Cato 的 answer 解释得很漂亮。

【讨论】:

  • 难以置信!该程序在 2.5 秒内完成。你能简单解释一下你的魔法代码的含义吗?
  • 如果您能解释禁用sync_with_stdio 会带来什么危险,以及为什么默认启用它,那就太好了。
  • 当然,乔丹和@qdii 我就补充一下。
  • @idontknoooo 如果有效,请接受我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-24
  • 2020-04-09
  • 2014-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多