Tôi đã mã hóa một ứng dụng rất đơn giản sử dụng Fibonacci fonction để so sánh số Parallel.ForEach
của TPL so với số parallel_for_each
của PPL và kết quả thực sự lạ, trên máy tính có 8 lõi, C# là 11 giây nhanh hơn rồi C++.C# TPL nhanh hơn C++ PPL?
Kết quả tương tự trên cả bản xem trước vs2010 và so với năm 2011. # mã
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);
}
}
}
C++ mã:
#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();
}
Bạn có thể xin vui lòng chỉ cho tôi, nơi một phần của c của tôi ++ mã tôi đang sai?
Width group_task i có cùng thời gian như C# code:
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();
Bạn có thể vui lòng đăng mã nguồn được định dạng đúng không? Các liên kết trống giữa các câu lệnh đặc biệt khó chịu, vì chúng buộc tôi phải di chuyển khá nhiều. –
Điều gì nhảy ra ngoài với tôi là bạn đang sử dụng các bộ sưu tập khác nhau trong các ví dụ của bạn. Phiên bản C# sử dụng hàng đợi trong khi phiên bản C++ sử dụng vectơ. –
Ngoài ra, bạn có chỉ định thời gian gọi hàm 'fibonacci' trong mỗi ví dụ không? –