Cha*_*han 6 c# task-parallel-library
我尝试了一个非常小的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace TPLExample {
class Program {
static void Main(string[] args) {
int[] dataItems = new int[100];
double[] resultItems = new double[100];
for (int i = 0; i < dataItems.Length; ++i) {
dataItems[i] = i;
}
Stopwatch stopwatch = new Stopwatch();
stopwatch.Reset();
stopwatch.Start();
Parallel.For(0, dataItems.Length, (index) => {
resultItems[index] = Math.Pow(dataItems[index], 2);
});
stopwatch.Stop();
Console.WriteLine("TPL Time elapsed: {0}", stopwatch.Elapsed);
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < dataItems.Length; ++i) {
resultItems[i] = Math.Pow(dataItems[i], 2);
}
stopwatch.Stop();
Console.WriteLine("Sequential Time elapsed: {0}", stopwatch.Elapsed);
WaitForEnterKey();
}
public static void WaitForEnterKey() {
Console.WriteLine("Press enter to finish");
Console.ReadLine();
}
public static void PrintMessage() {
Console.WriteLine("Message printed");
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
TPL Time elapsed: 00:00:00.0010670
Sequential Time elapsed: 00:00:00.0000178
Press enter to finish
Run Code Online (Sandbox Code Playgroud)
顺序循环比TPL快!这怎么可能?根据我的理解,计算中的计算Parallel.For将并行执行,所以它必须更快吗?
Str*_*ior 10
简单地说:对于只迭代超过一百个项目并执行一个小的数学运算,产生新线程并等待它们完成会产生比仅仅通过循环运行更多的开销.
根据我的理解,Parallel.For中的计算将并行执行,所以它必须更快吗?
通常情况下,当人们对计算机性能进行彻底的陈述时,这里有更多的变量,你无法真正做出这样的假设.例如,在你的for循环中,你所做的只是Math.Pow处理器可以非常快速地执行的操作.如果这是一个I/O密集型操作,要求每个线程等待很长时间,或者即使它是一系列处理器密集型操作,您将获得更多的并行处理(假设您有一个多线程处理器) .但事实上,创建和同步这些线程的开销远远大于并行性可能给你的任何优势.
| 归档时间: |
|
| 查看次数: |
2596 次 |
| 最近记录: |