using System.Diagnostics;
class TimeCalculator//视情况加public修饰符,下同
{
private readonly List<TimeMessage> calculations = new List<TimeMessage>();//初始化,后面实例方法需要用到
private readonly Stopwatch stopwatch = new Stopwatch();
public void Start()
{
stopwatch.Start();//开始计时
}
public void Stop(string name)
{
stopwatch.Stop();//结束计时
var calculation = new TimeMessage
{
Name = name,
Time = stopwatch.Elapsed
};
calculations.Add(calculation);//记录数据,存放到时间信息列表
stopwatch.Reset();//重置计时器
}
public void PrintResults()//打印时间信息列表
{
foreach (var calculation in calculations)
{
Console.WriteLine($"{calculation.Name}: {calculation.Time}");
}
}
public List<TimeMessage> ReturnResults()//返回时间信息列表
{
return calculations;
}
}
class TimeMessage
{
public string Name { get; set; }
public TimeSpan Time { get; set; }
}
class Test
{
static void Method1()
{
for (int i = 0; i < 100000; i++)
{
var a = i;
}
}
static void Method2()
{
for (int i = 0; i < 300000; i++)
{
var b = i;
}
}
static int Main(string[] args)
{
var calculator = new TimeCalculator();//实例化一个类(为这个类创建对象)
calculator.Start();//对象调用方法:开始计时
Method1();
calculator.Stop("Method1");//对象调用方法:结束计时并且登记名字
calculator.Start();
Method2();
calculator.Stop("Method2");
calculator.PrintResults();//打印计时结论
var calculresult = calculator.ReturnResults();//获取计时结论列表
return 0;
}
}