using both cores of cpu
我想在for循环中进行一些计算:
1 2 3 | for (int i=0; i< Math.Pow(10,8) ;i++){ //do some computation } |
但是当我运行时,它仅使用我的一个cpu内核(我在任务管理器中看到我的程序使用了50%的cpu)。
如何使用两个核心? 需要穿线吗?
如果它需要多线程,那么我无法中断循环,因为它填充了一个数组并将其用作索引增量,那么解决方案是什么(如果需要线程)。
例如,在下面的代码中,我以递增的方式填充数组P,并动态使用数组。
1 2 3 4 5 6 7 | void f(){/*do some computation*/} double[] P; for (int i=0; i< Math.Pow(10,8) ;i++){ if (some conditions with index i and f and array P occurs ) P[i]=f; } |
我的笔记本电脑是Intel Core 2 dou 2.2 GH。
does it needs threading?
是的,它确实。
您可以从TPL使用并行
1 2 3 4 5 | Parallel.For(0, (int)Math.Pow(10, 8), i => { // do some computation }); |
当然,如果可以单独计算数组中每个项目的值,则此解决方案适用。
看看:http://msdn.microsoft.com/zh-cn/library/system.threading.tasks.parallel.for(v=vs.110).aspx
您会在网上找到很多示例。