您好我正在为我的项目的一部分编写测试计划,我想知道如何衡量我的排序功能需要多长时间。我的尝试看起来像这样:
private void byIGNameToolStripMenuItem_Click(object sender, EventArgs e)
{
GameDB.Sort(new PlayerNameComparer());
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
}
但我收到编译错误:'DBProject.Form1.PlayerNameComparer.stopwatch' is a 'field' but is used like a 'type'
答案 0 :(得分:1)
这个答案是完全错误的,因为你在Compare
方法中并且在排序过程中被多次调用。
测试此方法的方法与此类似:
private void byIGNameToolStripMenuItem_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
GameDB.Sort(new PlayerNameComparer());
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}
同时考虑使用IComparer
的通用版本,因为它是强类型的,您无需从object
类型拆分到class
类型。
一个很好的例子可能是:
public class StringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
在你的情况下可以变成:
public class PlayerNameComparer : IComparer<Player>
{
public int Compare(Player x, Player y)
{
return x.playerIgName.CompareTo(y.playerIgName);
}
}
答案 1 :(得分:-2)
您正在类区域中执行语句,而不是在方法中执行; )
在PL语言中 - &gt; Nie mozesz wykonywać kodu w obrębie klasy, rób to w metodach : )
只需将它们放入方法
public int Compare(object x, object y)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int ret =((Player)x).playerIgName.CompareTo(((Player)y).playerIgName)
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
return ret;
}
但是该代码会针对您要排序的每个项目执行,因此如果您在排序之前启动手表会更好,并在此之后停止:)
private void byIGNameToolStripMenuItem_Click(object sender, EventArgs e)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
GameDB.Sort(new PlayerNameComparer());
stopwatch.Stop();
MessageBox.Show("Time Elapsed:" + stopwatch.ElapsedMilliseconds);
currentEntryShown = 0;
ShowData();
UpdatePrevNextBtnStatus();
}
public class PlayerNameComparer : IComparer
{
public int Compare(object x, object y)
{
return ((Player)x).playerIgName.CompareTo(((Player)y).playerIgName);
}
}