public Form1()
{
InitializeComponent();
Stopwatch sw = new Stopwatch();
sw.Start();
//string filePath = @"D:\cp.bin";
string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"cp.bin";//设置路径
using (FileStream fs = File.Create(filePath))//优化
{
/*需要使用内置的 Syncronized TextReader/Writer类
* 在复制内存时检测到可能的 I/O 争用条件。默认情况下,I/O 包不是线程安全的。
* 在多线程应用程序中,必须以线程安全方式(如 TextReader 或 TextWriter 的 Synchronized 方法返回的线程安全包装)访问流。
* 这也适用于 StreamWriter 和 StreamReader 这样的类。
*/
StreamWriter ObjWrites = default(StreamWriter);
ObjWrites = new StreamWriter(fs);
dynamic synws = StreamWriter.Synchronized(ObjWrites);
double t0 = 0, f0 = 100000;
//double beta = (f1 - f0) / t1;
double beta = 900000/4.194304;
double chirp = 0;
Parallel.For(0, 167772160, (i) =>
{
t0 += 0.000000025;
chirp = Math.Cos(Math.PI * (2 * f0 + beta * t0) * t0);
chirp = Math.Round(chirp * 2046);
chirp = chirp*2 + 2046;
synws.Write(chirp.ToString());
});
synws.Close();
ObjWrites.Close();
}
sw.Stop();
MessageBox.Show("耗时为: " + sw.ElapsedMilliseconds.ToString() + " ms");
}
耗时40多秒,经过性能检测,时间花在了写入文件上,见下图:
大家看看有什么方法能改善一下吗?时间能控制在20s内