,直到它变得清晰,一段代码创建了一个真正的瓶颈,我不会被人打扰太多关于性能。让我们假设你有这样的瓶颈,并测量以下代码的性能(这是在C#中,但我敢肯定,C++不会慢):
public class Rectangle
{
public int X { get; set; }
public int Y { get; set; }
public int W { get; set; }
public int H { get; set; }
public bool HitTest(int x, int y)
{
return x >= X && x < X + W && y >= Y && y < Y + H ? true : false;
}
}
我们有兴趣性能的HitTest()
方法,所以让我们来衡量它!
void PerformanceTest()
{
const int Iterations = 1000000;
Random rnd = new Random();
var rectangles = Enumerable.Range(1, 50).Select(
r => new Rectangle {
X = rnd.Next(1000),
Y = rnd.Next(1000),
W = rnd.Next(1000),
H = rnd.Next(1000)}).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < Iterations; i++)
{
rectangles.ForEach(r => r.HitTest(500, 500));
}
sw.Stop();
Console.WriteLine("Elapsed time: {0}ms. ({1}us per one iteration)",
sw.ElapsedMilliseconds,
(float)sw.ElapsedMilliseconds * 1000/Iterations);
}
在我的电脑上面的代码打印:
执行时间:701ms。 (每一次迭代0.701us)
正如你所看到的,它需要不到一微秒的命中测试50米的矩形。你真的觉得这个时间太长了吗?与创建幻想悬停效果的时间相比,你的程序还有其他什么?当然,只有你可以回答这个问题。
但我的故事的寓意是:不要试图预先优化,不花时间试图解决它可能不存在的一个问题。
使用PtInRect该函数。如果存在效率问题,请进行配置并进行更改。 – 2012-03-02 15:53:00