我编写了一个非常简单的应用程序,它使用Fibonacci函数来比较TPL Parallel.ForEach 和PPL parallel_for_each,结果非常奇怪,在具有8个内核的PC上,c#比 c ++ 快11秒.
vs2010和2011预览都有相同的结果.
C#代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var ll = new ConcurrentQueue<Tuple<int, int>>();
var a = new int[12] { 40, 41, 42, 43, 44, 45, 46, 47, 35, 25, 36, 37 };
long elapsed = time_call(() =>
{
Parallel.ForEach(a, (n) => { ll.Enqueue(new Tuple<int, int>(n, fibonacci(n))); });
});
Console.WriteLine("TPL C# elapsed time: " + elapsed + "\n\r");
foreach (var ss in ll)
{
Console.WriteLine(String.Format("fib<{0}>: {1}", ss.Item1, +ss.Item2));
}
Console.ReadLine();
}
static long time_call(Action f)
{
var p = Stopwatch.StartNew();
p.Start();
f();
p.Stop();
return p.ElapsedMilliseconds;
}
Computes the nth Fibonacci number.
static int fibonacci(int n)
{
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}
Run Code Online (Sandbox Code Playgroud)
c ++代码:
#include <windows.h>
#include <ppl.h>
#include <concurrent_vector.h>
#include <array>
#include <tuple>
#include <algorithm>
#include <iostream>
using namespace Concurrency;
using namespace std;
template <class Function>
__int64 time_call(Function&& f) {
__int64 begin = GetTickCount();
f();
return GetTickCount() - begin;
}
// Computes the nth Fibonacci number.
int fibonacci(int n) {
if (n < 2) return n;
return fibonacci(n-1) + fibonacci(n-2);
}
int wmain() {
__int64 elapsed;
array<int, 12> a ={ 40, 41, 42, 43, 44, 45, 46, 47, 35, 25, 36, 37 };
concurrent_vector<tuple<int,int>> results2;
elapsed = time_call([&]{
parallel_for_each(a.begin(), a.end(), [&](int n) {
results2.push_back(make_tuple(n, fibonacci(n)));
});
});
wcout << L"PPL time: " << elapsed << L" ms" << endl << endl;
for_each (results2.begin(), results2.end(), [](tuple<int,int>& pair) {
wcout << L"fib(" << get<0>(pair) << L"): " << get<1>(pair) << endl;
});
cin.ignore();
}
Run Code Online (Sandbox Code Playgroud)
你能指点我,我的c ++代码的一部分我错了吗?
宽度group_task我有像c#代码一样的时间:
task_group tasks;
elapsed = time_call([&]
{
for_each(begin(a), end(a), [&](int n)
{
tasks.run([&,n]{results2.push_back(make_tuple(n, fibonacci(n)));});
});
tasks.wait();
Run Code Online (Sandbox Code Playgroud)
以下是Rahul v Patil微软团队的解释
你好,
谢谢你提出这个问题.实际上,您已经确定了与*的默认并行相关的开销 - 尤其是当迭代次数很少且工作大小可变时.默认并行开始时将工作分解为8个块(在8个核心上).随着工作的完成,工作是动态负载平衡的.默认情况下在大多数情况下(大量迭代)都很有效,并且当每次迭代的基础工作都没有被很好地理解时(假设你调用了一个库) - 但在某些情况下确实会带来不可接受的开销.
解决方案正是您在备用实现中确定的解决方案.为此,我们将在下一版本的Visual Studio中为分区程序提供一个名为"simple"的并行程序,它与您描述的替代实现类似,并且具有更好的性能.
PS:每个实现的C#和C++并行在迭代过程中使用略有不同的算法 - 因此,根据工作负载,您将看到略微不同的性能特征.
问候
小智 5
您的代码存在一些问题,让我们逐个解决:
使用递归来计算Fibonacci会导致进程使用过多的内存,因为它使用调用堆栈来计算结果.具有递归Fibonacci意味着您不是在比较C#/ C++并行框架,而是在比较调用堆栈机制.你可以更快地计算斐波那契:
int fibonacci(int n)
{
int curr = 1, prev = 0, total = 0;
for (int i = 0; i < n; i++)
{
int pc = curr;
curr += prev;
total += curr;
prev = pc;
}
return total;
}
Run Code Online (Sandbox Code Playgroud)
有了这个功能,我必须运行至少100万次以获得可测量的值.
使用GetTickCount64而不是GetTickCount:
template <class Function>
__int64 time_call(Function&& f)
{
__int64 begin = ::GetTickCount64();
f();
return GetTickCount64() - begin;
}
Run Code Online (Sandbox Code Playgroud)
以这么小的身体运行parallel_for实际上可能对性能有害.最好使用更细粒度的仿函数.
考虑到这些特性,这里是C++中的代码:
// ParallelFibo.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
#include <ppl.h>
#include <concurrent_vector.h>
#include <array>
#include <tuple>
#include <algorithm>
#include <iostream>
#include <random>
using namespace Concurrency;
using namespace std;
template <class Function>
__int64 time_call(Function&& f)
{
__int64 begin = ::GetTickCount64();
f();
return GetTickCount64() - begin;
}
// Computes the nth Fibonacci number.
inline int fibonacci(int n)
{
int curr = 1, prev = 0, total = 0;
for (int i = 0; i < n; i++)
{
int pc = curr;
curr += prev;
total += curr;
prev = pc;
}
return total;
}
#define NUMBER_OF_REPETITIONS 1000000
#define MIN_FIBO 37
#define MAX_FIBO 49
int main()
{
__int64 elapsed;
vector<int> v;
for (int i = MIN_FIBO; i < MAX_FIBO; i++)
{
v.emplace_back(i);
}
concurrent_vector<tuple<int, int>> results;
elapsed = time_call([&] {
parallel_for(MIN_FIBO, MAX_FIBO, [&](int n) {
for (int i = 0; i < NUMBER_OF_REPETITIONS; i++)
{
results.push_back(make_tuple(n, fibonacci(n)));
}
});
});
wcout << L"PPL time: " << elapsed << L" ms" << endl << endl;
cin.ignore();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是C#中的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Diagnostics;
namespace ParallelFiboCS
{
class Program
{
const int NUMBER_OF_REPETITIONS = 1000000;
const int MIN_FIBO = 37;
const int MAX_FIBO = 49;
static void Main(string[] args)
{
var ll = new ConcurrentQueue<Tuple<int, int>>();
var a = new int[MAX_FIBO - MIN_FIBO];
for (int i = MIN_FIBO; i < MAX_FIBO; i++)
{
a[i - MIN_FIBO] = i;
}
long elapsed = time_call(() =>
{
Parallel.ForEach(a, (n) =>
{
for (int i = 0; i < NUMBER_OF_REPETITIONS; i++)
{
ll.Enqueue(new Tuple<int, int>(n, fibonacci(n)));
}
});
});
Console.WriteLine("TPL C# elapsed time: " + elapsed + "\n\r");
Console.ReadLine();
}
static long time_call(Action f)
{
var p = Stopwatch.StartNew();
p.Start();
f();
p.Stop();
return p.ElapsedMilliseconds;
}
static int fibonacci(int n)
{
int curr = 1, prev = 0, total = 0;
for (int i = 0; i < n; i++)
{
int pc = curr;
curr += prev;
total += curr;
prev = pc;
}
return total;
}
}
}
Run Code Online (Sandbox Code Playgroud)
平均时间为37到49之间的数字运行1200万斐波纳契计算:
C++:513ms
C#:2527ms
用于测量本机端传递时间的 GetTickCount (http://msdn.microsoft.com/en-us/library/windows/desktop/ms724408%28v=vs.85%29.aspx) 函数根本不精确。描述是这样说的:
“GetTickCount 函数的分辨率受限于系统定时器的分辨率,通常在 10 毫秒到 16 毫秒的范围内。”
根据我的经验,在 Windows Vista 及更高版本上使用 GetSystemTime 会产生更好的结果(如果我没记错的话,在 Win XP 上,分辨率与滴答计数有点相同)。或者更好的是,您可以使用一些提供亚密耳分辨率的其他 API 来进行细粒度测量。在您的情况下,构建大型数据集可能会更有帮助,以获得一些有意义的数据。