[英]How to measure total execution time of a parallel task or multi-thread program in c#?
I am a novice in C#/.NET.我是 C#/.NET 的新手。 Here I am trying to run the following parallel tasks and measure the total execution time.
在这里,我尝试运行以下并行任务并测量总执行时间。
But after running the code the execution time is showing just > 6 ms which is way less than it is supposed to be.但是在运行代码后,执行时间显示为 > 6 ms,这比预期的要少得多。 I am not sure if there is any misplacing of the Stopwatch() function that's giving this unexpected result.
我不确定 Stopwatch() 函数是否有任何错误放置导致这种意外结果。
Your help will be appreciated :您的帮助将不胜感激:
namespace Tests
{
class Prod
{
static void Main(string[] args)
{
Stopwatch s = new Stopwatch();
s.Start();
{
Task T1 = Task.Run(() =>
{
for (int i = 0; i <= 5000; i++)
Console.WriteLine("Test1:" + i);
});
Task T2 = Task.Run(() =>
{
for (int i = 0; i <= 5000; i++)
Console.WriteLine("Test2:" + i);
});
Task T3 = Task.Run(() =>
{
for (int i = 0; i <= 5000; i++)
Console.WriteLine("Test3:" + i);
});
}
s.Stop();
Console.WriteLine("Press any key to quit");
Console.ReadKey();
Console.WriteLine("Total Task Ellapsed time -> {0}", s.ElapsedMilliseconds);
}
}
}
You need a Task.WaitAll before the stop of the Stopwatch
( s.Stop()
in your code)在停止
Stopwatch
(代码中的s.Stop()
之前,您需要一个Task.WaitAll
for example:例如:
Task.WaitAll(T1,T2,T3);
s.Stop();
One solution would be to wait for all Tasks to be completed using Task.WaitAll一种解决方案是使用Task.WaitAll等待所有任务完成
Task.WaitAll(T1,T2,T3);
Complete Code完整代码
Stopwatch s = new Stopwatch();
s.Start();
{
Task T1 = Task.Run(() =>
{
for (int i = 0; i <= 5000; i++)
Console.WriteLine("Test1:" + i);
});
Task T2 = Task.Run(() =>
{
for (int i = 0; i <= 5000; i++)
Console.WriteLine("Test2:" + i);
});
Task T3 = Task.Run(() =>
{
for (int i = 0; i <= 5000; i++)
Console.WriteLine("Test3:" + i);
});
Task.WaitAll(T1,T2,T3); // Change here
}
s.Stop();
Console.WriteLine("Press any key to quit");
Console.WriteLine("Total Task Ellapsed time -> {0}", s.ElapsedMilliseconds);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.