Parallel 替代 For 循环,为你的程序提升效率吧
2013-01-08 14:55
274 查看
现代的计算机以前不像以前的计算机了,所以,我们的代码也需要优化了,如果仍然按照旧的处理方式,就不能将用户的计算机性能发挥出来,这也是提升用户体验的一种方式!
Parallel 是C#4.0 提供一种并行的处理方式,如果你的的For循环是可以并行的且涉及大量的工作,那么请用Parallel的For替换你的for循环吧,这会大大提升程序的效率
先贴代码吧:
static int[] _Data;
static Stopwatch _Sw = new Stopwatch();
static void Main(string[] args)
{
//prepare data
_Data = new int[10];
for (int i = 0; i < _Data.Length; i++)
_Data[i] = i;
_Sw.Start();
NewMethod();
_Sw.Stop();
Console.WriteLine("new use time :{0}", _Sw.ElapsedMilliseconds);
_Sw.Restart();
OldMethod();
Console.WriteLine("old use time :{0}", _Sw.ElapsedMilliseconds);
Console.ReadKey();
}
static void NewMethod()
{
Parallel.For(0, _Data.Length, DoMethod);
}
static void OldMethod()
{
for (int i = 0; i < _Data.Length; i++)
DoMethod(i);
}
static void DoMethod(int i)
{
//输出当前的i 并模拟耗时操作
Console.WriteLine("Do:{0}", i);
Thread.Sleep(500);
}
Parallel.For是自动创建了多个线程,并行的执行DoMethod,所以每次执行都是无序的,如果你的的For循环是可以并行的且涉及大量的工作,,那么用Parallel吧,可以看到cpu利用率猛的飙了上去哦
ps:线程是昂贵的,如果是简单的循环,使用for循环吧,因为创建并行任务和执行上下文切换的时间将超过使用并行节省的时间。
Parallel 是C#4.0 提供一种并行的处理方式,如果你的的For循环是可以并行的且涉及大量的工作,那么请用Parallel的For替换你的for循环吧,这会大大提升程序的效率
先贴代码吧:
static int[] _Data;
static Stopwatch _Sw = new Stopwatch();
static void Main(string[] args)
{
//prepare data
_Data = new int[10];
for (int i = 0; i < _Data.Length; i++)
_Data[i] = i;
_Sw.Start();
NewMethod();
_Sw.Stop();
Console.WriteLine("new use time :{0}", _Sw.ElapsedMilliseconds);
_Sw.Restart();
OldMethod();
Console.WriteLine("old use time :{0}", _Sw.ElapsedMilliseconds);
Console.ReadKey();
}
static void NewMethod()
{
Parallel.For(0, _Data.Length, DoMethod);
}
static void OldMethod()
{
for (int i = 0; i < _Data.Length; i++)
DoMethod(i);
}
static void DoMethod(int i)
{
//输出当前的i 并模拟耗时操作
Console.WriteLine("Do:{0}", i);
Thread.Sleep(500);
}
Parallel.For是自动创建了多个线程,并行的执行DoMethod,所以每次执行都是无序的,如果你的的For循环是可以并行的且涉及大量的工作,,那么用Parallel吧,可以看到cpu利用率猛的飙了上去哦
ps:线程是昂贵的,如果是简单的循环,使用for循环吧,因为创建并行任务和执行上下文切换的时间将超过使用并行节省的时间。
相关文章推荐
- OpenMP程序 for 循环并行的效率
- 探究数组排序提升Python程序的循环的运行效率的原因
- OpenMP: 程序for循环并行效率优化
- 开发 | 提升 1 倍运行效率!有了这些技巧,你的小程序也能快如闪电
- 提升Flex程序效率若干技巧
- 使用矩阵运算替代 for 循环实现信号的DTFT
- 使用两个for循环的时候,会非常慢,效率不高,使用构造字典,效率快了不少一点点!
- 提升Python程序运行效率的6个方法
- 用 while 循环编程,输出 10 到 0 递减的自然数。然后用 for 循环重写该程序
- JavaScript的for循环写法及效率
- swift中c风格的for循环执行效率
- 微信小程序数据使用wx:for循环展示
- for、foreach和MoveNext循环效率粗比较
- 提升程序效率的法宝
- for 循环性能比较 提高for循环的效率
- 简单编程(六)使用for循环语句 编写程序1+2+3+...........+100
- [第3天] 程序的控制结构 (循环)[while]、[do while]、[for]
- 一段效率很高的for循环语句使用方法
- for循环中i++与++i的效率探究
- 微信小程序的页面循环 for