I have a problem with trying to get the job done under 4 seconds using either parallel or task schedule or whatever. The script is simple, it will try to process 100 times all at once and wait for the result. My pc is E5-2603 Xeon processor(4 core, 4 thread, 1.80GHz) with 16GB and it took forever to process 100 hundred tasks.
What can I do to speed up the process?
Test script
static void Main(string[] args)
{
//Monitor performance
Stopwatch totalTime = new Stopwatch();
//Test case # 1
totalTime.Start();
TaskTechnique();
totalTime.Stop();
Console.WriteLine("TaskTechnique total time: " + totalTime.Elapsed.TotalSeconds);
Console.WriteLine("--------------------------------------");
//Test case #2
totalTime.Reset();
totalTime.Start();
ParalelelTechnique();
totalTime.Stop();
Console.WriteLine("ParalelelTechnique total time: " + totalTime.Elapsed.TotalSeconds);
Console.WriteLine("--------------------------------------");
}
When Task Class Definition Namespace: System.Threading.Tasks
It tooks 21 seconds to process 100 little tasks. The code is below
/// <summary>
/// Using task to process all tasks
/// </summary>
private static void TaskTechnique()
{
//Test case 1 process all 100 tasks at once
List<Task<string>> tasks = new List<Task<string>>();
for (int i = 0; i < 100; i++)
{
tasks.Add(
Task.Factory.StartNew
(
() =>
{
return MrDelay(i);
}
)
);
}
Task.WaitAll(tasks.ToArray());//Wait until finished
}
And when I used Parallel, it took 33 seconds to process.
/// <summary>
/// Using Paralelel to process 100 times
/// </summary>
private static void ParalelelTechnique()
{
//Monitor performance
Stopwatch startTime = new Stopwatch();
//Test case 2 using parallel
startTime.Restart();
int maxTask = 100;
var result = Parallel.For
(
1, 101,
new ParallelOptions { MaxDegreeOfParallelism = maxTask },
(i, state) =>
{
Console.WriteLine("Beginning iteration {0} at ", i, DateTime.Now.ToLocalTime());
string longTaskResult = MrDelay(i);
Console.WriteLine("Completed iteration {0} result at : {1}", i, longTaskResult);
}
);
startTime.Stop();
Console.WriteLine("test case 2: " + startTime.Elapsed.TotalSeconds);
}
Delay process code.
/// <summary>
/// Just to slow down the test to 3 seconds before return the data back
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private static string MrDelay(int id)
{
//Delay 3 seconds then return the result
System.Threading.Thread.Sleep(3000);
return "ok request id: " + id.ToString() + " processed time: " + DateTime.Now.ToLocalTime();
}