【300分散分,推荐一个不新不老的技术】我们写的程序真正用到多核了结构的能量了吗?
假设我们要把一个目录下的所有文件和子目录复制到另外一个目录下,我们如何让运行时间只有原来的一半,甚至四分之一?!
首先你可以下载微软 Parallel Extensions to the .NET Framework 的2008年6月预览版,这是一个大概300k左右的dll,放入你的项目,可以引用他的 using System.Threading 命名空间,你就可以写出代码:
private static void CopyDir(DirectoryInfo s, DirectoryInfo d){ if (!d.Exists) d.Create(); Parallel.Invoke( () => { Parallel.ForEach(s.GetFiles(), f => { var t = new FileInfo(Path.Combine(d.FullName, f.Name)); f.CopyTo(t.FullName); Total++; }); }, () => { Parallel.ForEach(s.GetDirectories(), subs => { var subd = new DirectoryInfo(Path.Combine(d.FullName, subs.Name)); CopyDir(subs, subd); }); });}private static TimeSpan Test(){ var w = new Stopwatch(); w.Start(); CopyDir(new DirectoryInfo("e:\\test"), new DirectoryInfo("e:\\test1")); w.Stop(); return w.Elapsed;}