gpt4 book ai didi

c# - 快速将非常大的 BigInteger 写入 .txt 文件

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:14 27 4
gpt4 key购买 nike

我需要一种更快的方法来将 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();

输出 160 万位数字大约需要 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();
}
}

我机器上的输出:

That took 13 milliseconds

写入文件非常快,文件系统缓存使其成为内存到内存的副本。在您的程序停止运行很久之后,操作系统才将其延迟写入磁盘。当您写入的数据超出缓存中的容量时,它永远无法隐藏缓慢的磁盘写入速度。在任何现代机器上你都离不开它,它们有很多 RAM 并且可以轻松存储 1 GB。 1.6 兆字节是牙线。

所以您知道实际上是 BigInteger.ToString() 太慢了。是的。它将 Big Mother 存储在基数 2 中,使数学运算尽可能快。像 base 2 这样的处理器,他们用 2 个手指计数。转换为以 10 为底的人类格式,这很昂贵。它需要除法,这是使用处理器所能做的最昂贵的事情之一。

关于c# - 快速将非常大的 BigInteger 写入 .txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377766/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com