public Form1()
{
InitializeComponent();
Stopwatch sw = new Stopwatch();
sw.Start();
//string filePath = @"D:\cp.bin";
string filePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"cp.txt";//设置路径将文件保存在目标文件下
using (FileStream fs = File.Create(filePath))//优化
{
double t0 = 0, f0 = 100000d;
//double beta = (f1 - f0) / t1;
double beta = 900000d/4.194304d;
double chirp = 0;
for(int i=0; i<=167772160; i++)
{
t0 += 0.000000025;
chirp = Math.Cos(Math.PI * (2 * f0 + beta * t0) * t0);
chirp = Math.Round(chirp * 2046);
chirp = chirp*2 + 2046;
byte[] b=Encoding.Unicode.GetBytes(chirp.ToString());
fs.Write(b, 0, b.Length);
}
}
sw.Stop();
MessageBox.Show("耗时为: " + sw.ElapsedMilliseconds.ToString() + " ms");
}
写文件应该是个很耗时的操作,把需要转换的数据先保存到内存中,循环完成后,再一次性把所有数据写到文件里;
http://blog.csdn.net/swjtu_yhz/article/details/72778811 写文件确实需要优化 看下对你有没帮助
For循环次数太多了,而且循环里面只有一个变量t0 需要累加 ,
分成多组分别计算chirp. 实测分16组的话,每组只需4s 出结果。
开16个线程同时分别跑。
主要还是For循环里的数学计算这块的优化。
写文件的操作C#内部有优化,copy了一些注释如下(http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ddd3),
public override void Write(byte[] array, int offset, int count) {
...
// If our buffer has data in it, copy data from the user's array into
// the buffer, and if we can fit it all there, return. Otherwise, write
// the buffer to disk and copy any remaining data into our buffer.
// The assumption here is memcpy is cheaper than disk (or net) IO.
// (10 milliseconds to disk vs. ~20-30 microseconds for a 4K memcpy)
// So the extra copying will reduce the total number of writes, in
// non-pathological cases (ie, write 1 byte, then write for the buffer
// size repeatedly)
...
}
io操作很耗资源
所以尽量把fs.Write(b, 0, b.Length);这块代码写到外面
另外由于循环次数比较多。乘法除法是运算里最耗资源的,所以建议循环内的乘法可以改为相应的位移操作。
public void Thread9()
{
Stopwatch sw = new Stopwatch();
sw.Start();
string filePath1 = System.AppDomain.CurrentDomain.
SetupInformation.ApplicationBase + @"cp9.txt";
double t0 = 1.6577216d, f0 = 100000d;
double beta = 900000d / 4.194304d;
double chirp = 0;
using (FileStream fs1 = File.Open(filePath1, FileMode.OpenOrCreate, FileAccess.Write))
{
for (int i = 66308865; i <= 74597472; i++)
{
chirp = Math.Cos(Math.PI * (2 * f0 + beta * t0) * t0);
t0 += 0.000000025d;
chirp = Math.Round(chirp * 2046);
chirp = chirp * 2 + 2046;
byte[] b = Encoding.Unicode.GetBytes(chirp.ToString());
fs1.Write(b, 0, b.Length);
}
sw.Stop();
Console.WriteLine("线程9耗时为:{0} ms",
sw.ElapsedMilliseconds.ToString());
}
}
每个线程里的代码都是这样的,for循环的次数都相同,但时间完全不同