This is a little sample to choose parallel or not. It is used LINQ to object.
Example of source code:
DateTime start = DateTime.MinValue;
DateTime stop = DateTime.MinValue;
TimeSpan seleisih;
Console.WriteLine("Sequential");
IEnumerable<int> cobaAss = Enumerable.Range(0, 30000000);
var hh = from x in cobaAss
where x % 3 == 0
select Math.Sqrt(x);
start = DateTime.Now;
foreach (var item in hh)
{
double x = item * 1.5;
}
stop = DateTime.Now;
seleisih = stop - start;
Console.WriteLine("Start : {0}", start);
Console.WriteLine("Stop : {0}", stop);
Console.WriteLine("Selisih (tick) : {0}", seleisih.Ticks);
// --
Console.WriteLine("Parallel");
cobaAss = Enumerable.Range(0, 30000000);
hh = from x in cobaAss.AsParallel()
where x % 3 == 0
select Math.Sqrt(x);
start = DateTime.Now;
//Parallel.ForEach<double>(hh, (item) => { });
foreach (var item in hh)
{
double x = item * 1.5;
}
stop = DateTime.Now;
seleisih = stop - start;
Console.WriteLine("Start : {0}", start);
Console.WriteLine("Stop : {0}", stop);
Console.WriteLine("Selisih (tick) : {0}", seleisih.Ticks);
Console.WriteLine("Parallel Doit manually");
var cobaAss1 = Enumerable.Range(0, 10000000);
var cobaAss2 = Enumerable.Range(10000000, 10000000);
var cobaAss3 = Enumerable.Range(20000000, 10000000);
var hh1 = from x in cobaAss
where x % 3 == 0
select Math.Sqrt(x);
var hh2 = from x in cobaAss
where x % 3 == 0
select Math.Sqrt(x);
var hh3 = from x in cobaAss
where x % 3 == 0
select Math.Sqrt(x);
start = DateTime.Now;
Parallel.Invoke(
() =>
{
foreach (var item in hh1)
{
double x = item * 1.5;
}
},
() =>
{
foreach (var item in hh2)
{
double x = item * 1.5;
}
},
() =>
{
foreach (var item in hh3)
{
double x = item * 1.5;
}
});
stop = DateTime.Now;
seleisih = stop - start;
Console.WriteLine("Start : {0}", start);
Console.WriteLine("Stop : {0}", stop);
Console.WriteLine("Selisih (tick) : {0}", seleisih.Ticks);
Console.ReadLine();
I use console project to use it. You can try your own test
Below is the result:
This is strange since sequential is faster than parallel using AsParallel() or manually to do in parallel.
Summary: Parallelism is not always fasten the query
0 comments:
Post a Comment