更新时间:2023-11-22 21:31:34
我主要按照你的方式尝试了它,花了39秒。当然,我不知道你的秒表课程的内容,但是当我打电话给我的 ElapsedTime $ c时,我所做的就是返回 TimeSpan
$ c>方法。我也只使用 string.Concat
结束值只调用 Console.Writeline
。
I tried it mostly your way and it took 39 seconds. Granted, I don't know the contents of your Stopwatch class, but all mine does is return aTimeSpan
when I call myElapsedTime
method. I'm also making only one call toConsole.Writeline
with astring.Concat
endated value.
public class StopWatch
{
public DateTime StartTime { get; set; }
public void Start()
{
this.StartTime = DateTime.Now;
}
public TimeSpan ElapsedTime()
{
return (DateTime.Now - this.StartTime);
}
}
static void Main(string[] args)
{
string str = Console.ReadLine();
if (str == "start")
{
StopWatch sw = new StopWatch();
sw.Start();
for (int i = 1; i < 200000; i++)
{
Console.WriteLine(string.Concat("Acccessed Value: ", i.ToString(), ", Time: ", sw.ElapsedTime().ToString()));
}
}
Console.Read();
}
出于好奇,我尝试了运行单个应用程序的多线程方法。这也是47秒。
Out of curiosity, I tried a multi-threaded approach running a single app. This too 47 seconds.
static void Main(string[] args)
{
string str = Console.ReadLine();
if (str == "start")
{
StopWatch sw = new StopWatch();
sw.Start();
Parallel.Invoke(()=>
{
for (int i = 1; i < 200000; i++)
{
Console.WriteLine(string.Concat("Thread 1, Acccessed Value: ", i.ToString(), ", Time: ", sw.ElapsedTime().ToString()));
}
},
()=>
{
for (int i = 1; i < 200000; i++)
{
Console.WriteLine(string.Concat("Thread 2, Acccessed Value: ", i.ToString(), ", Time: ", sw.ElapsedTime().ToString()));
}
});
}
Console.Read();
}
最后,我想知道共享相同的秒表是否会导致某种自我延迟,所以我做了这个,导致大约49秒的时间流逝。
And finally, I wondered if sharing the same stopwatch might be causing some sort of self-induced delays, so I did this, which resulted in about 49 seconds of elapsed timed.
static void Main(string[] args)
{
string str = Console.ReadLine();
if (str == "start")
{
StopWatch sw = new StopWatch();
sw.Start();
Parallel.Invoke(()=>RunTask(1), ()=>RunTask(2));
}
Console.Read();
}
private static void RunTask(int taskno)
{
StopWatch sw = new StopWatch();
sw.Start();
string taskNumber = taskno.ToString();
for (int i = 1; i < 200000; i++)
{
Console.WriteLine(string.Concat("Thread ", taskNumber," , Acccessed Value: ", i.ToString(), ", Time: ", sw.ElapsedTime().ToString()));
}
}