将一个非常大的BigInteger快速写入.txt文件

Joh*_*tch 1 c# file-io biginteger

我需要一种更快捷的方式将160万位BigInteger输出到文件中.我现在正在使用此代码.

FileStream fs1 = new FileStream("C:\\Output\\Final\\BigInteger.txt",  FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(fs1);
writer.WriteLine(big);
writer.Close();
Run Code Online (Sandbox Code Playgroud)

输出160万位数字大约需要5分钟.有什么方法可以加快速度吗?

Han*_*ant 5

这是一个非常愚蠢的问题,没有实际用途.但确切地知道处理器周期的使用位置始终很重要.你抱怨写一个文件花了太长时间.那么,你确定它实际上是文件慢吗?或者它是BigInteger.ToString()那么慢?

找出答案的最佳方法就是写文件,这样你就可以解决问题了:

using System;
using System.Text;
using System.IO;

class Program {
    static void Main(string[] args) {
        var big = new StringBuilder(1600 * 1000);
        big.Append('0', big.Capacity);
        var sw = System.Diagnostics.Stopwatch.StartNew();
        // Your code here
        FileStream fs1 = new FileStream("BigInteger.txt",  FileMode.OpenOrCreate, FileAccess.Write);
        StreamWriter writer = new StreamWriter(fs1);
        writer.WriteLine(big);
        writer.Close();
        // End of your code
        sw.Stop();
        Console.WriteLine("That took {0} milliseconds", sw.ElapsedMilliseconds);
        Console.ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

我机器上的输出:

That took 13 milliseconds
Run Code Online (Sandbox Code Playgroud)

编写文件非常快,文件系统缓存使其成为内存到内存的副本.在程序停止运行很久之后,操作系统会懒惰地将其写入磁盘.当您写入的数据超出缓存容量时,它只能隐藏慢速磁盘写入速度.你在任何现代机器上都不是那么接近,它们有很多内存并且可以轻松存储千兆字节.1.6兆字母是牙线.

所以你知道它实际上是BigInteger.ToString()这么慢.是的.它将Big Mother存储在base 2中,使数学尽可能快.像base 2这样的处理器,用2个手指计数.转换为人类格式,基础10,这是昂贵的.它需要分区,这是处理器中最昂贵的事情之一.