Gerald Gonzales Gerald Gonzales - 4 years ago 107
C# Question

Arithmetic operations using console application

I am trying to create an application to record the time elapsed per machine using simple arithmetic operations.

Using console application, with parameters of number of loop and the threads to use with the code below:

public static Int64 IterationCount { get; set; }

static void Main(string[] args)
{
int iterations = int.Parse(args[0]);
int threads = int.Parse(args[1]);

IterationCount = iterations * 1000000000;

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < threads; i++)
{
Task.Factory.StartNew(() => Calculate());
Task.WaitAll();
}
sw.Stop();

Console.WriteLine("Elapsed={0}", sw.Elapsed);
}


And my
Calculate
method:

private static void Calculate()
{
for (int i = 0; i < IterationCount; i++)
{
a = 1 + 2;
b = 1 - 2;
c = 1 * 2;
a = 1 / 2;
}
}


Now I think this is not working because the result of my elapsed time when I entered 10 iterations (I am multiplying the first parameter to 1 billion: 10 * 1,000,000,000) and 4 threads is:

00:00:00:0119747


Any thing I missed?

Answer Source

Your call to Task.WaitAll() has no effect as the signature of the function is

public static void WaitAll(params Task[] tasks).

You see, you can supply a variable count of Tasks to wait for and you call this function with no task; so it will not wait at all.

If you replace your code by the following, you will see the effect.

Task[] tasks = new Task[threads];
for (int i = 0; i < threads; i++)
{
    tasks[i] = Task.Factory.StartNew(() => Calculate());
}
Task.WaitAll(tasks);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download