[英]Arithmetic operations using console application
我正在尝试创建一个应用程序,以使用简单的算术运算来记录每台计算机经过的时间。
使用控制台应用程序,其参数为循环数和要与以下代码一起使用的线程:
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);
}
而我的Calculate
方法:
private static void Calculate()
{
for (int i = 0; i < IterationCount; i++)
{
a = 1 + 2;
b = 1 - 2;
c = 1 * 2;
a = 1 / 2;
}
}
现在我认为这是行不通的,因为当我输入10次迭代(我将第一个参数乘以10亿:10 * 1,000,000,000)并经过4个线程时,经过时间的结果是:
00:00:00:0119747
我错过了什么吗?
原来我的评论是正确的。 如果我将Calculate
方法的内容复制到Visual Studio中:
private static void Calculate()
{
for (int i = 0; i < IterationCount; i++)
{
a = 1 + 2;
b = 1 - 2;
c = 1 * 2;
d = 1 / 2;
}
}
编译后,生成的C#代码如下所示:
private static void Calculate()
{
for (int i = 0; i < Program.IterationCount; i++)
{
Program.a = 3;
Program.b = -1;
Program.c = 2;
Program.d = 0;
}
}
相反,您将不得不将一个常量变成变量:
private static void Calculate()
{
int x = 1;
for (int i = 0; i < IterationCount; i++)
{
a = x + 2;
b = x - 2;
c = x * 2;
d = x / 2;
}
}
该代码变为:
private static void Calculate()
{
int x = 1;
for (int i = 0; i < Program.IterationCount; i++)
{
Program.a = x + 2;
Program.b = x - 2;
Program.c = x * 2;
Program.d = x / 2;
}
}
您对Task.WaitAll()
调用无效,因为该函数的签名为
public static void WaitAll(params Task[] tasks)
。
您会看到,您可以提供可变数量的Tasks
等待,然后不执行任何任务就调用此函数。 因此它根本不会等待。
如果用以下代码替换代码,则会看到效果。
Task[] tasks = new Task[threads];
for (int i = 0; i < threads; i++)
{
tasks[i] = Task.Factory.StartNew(() => Calculate());
}
Task.WaitAll(tasks);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.