优化前的代码如下所示,这是一个旋转点的函数,其中Sin(Angle),Cos(Angle)都各运算了两次,因此存在冗余计算。
通过2次优化 效率有 2.2秒 提升到 1.7秒,再提升到1.5秒。冗余计算优化还是非常有效果的
using System;
using System.Drawing;
namespace speed
{
class Program
{
static void Main(string[] args)
{
int i;
Point pt = new Point(15, 78);
double angle = 45d;
DateTime dt = DateTime.Now;
for (i = 0; i < 10000000; i++)
{
RotatePt_1(angle, pt);
}
TimeSpan ts = DateTime.Now - dt;
Console.WriteLine("RotatePt_1 cost time {0}", ts.ToString());
dt = DateTime.Now;
for (i = 0; i < 10000000; i++)
{
RotatePt_2(angle, pt);
}
ts = DateTime.Now - dt;
Console.WriteLine("RotatePt_2 cost time {0}", ts.ToString());
dt = DateTime.Now;
for (i = 0; i < 10000000; i++)
{
RotatePt_3(angle, pt);
}
ts = DateTime.Now - dt;
Console.WriteLine("RotatePt_3 cost time {0}", ts.ToString());
Console.Read();
}
static Point RotatePt_1(double angle, Point pt)
{
Point pRet = new Point();
angle = -angle;
pRet.X = (int)((double)pt.X * Math.Cos(angle) - (double)pt.Y * Math.Sin(angle));
pRet.Y = (int)((double)pt.X * Math.Sin(angle) + (double)pt.Y * Math.Cos(angle));
return pRet;
}
static Point RotatePt_2(double angle, Point pt)
{
Point pRet = new Point();
angle = -angle;
double SIN_ANGLE = Math.Sin(angle);
double COS_ANGLE = Math.Cos(angle);
pRet.X = (int)(pt.X * COS_ANGLE - pt.Y * SIN_ANGLE);
pRet.Y = (int)(pt.X * SIN_ANGLE + pt.Y * COS_ANGLE);
return pRet;
}
static Point RotatePt_3(double angle, Point pt)
{
angle = -angle;
double SIN_ANGLE = Math.Sin(angle);
double COS_ANGLE = Math.Cos(angle);
return new Point((int)(pt.X * COS_ANGLE - pt.Y * SIN_ANGLE),
(int)(pt.X * SIN_ANGLE + pt.Y * COS_ANGLE));
}
}
}
RotatePt_1 cost time 00:00:02.2381280
RotatePt_2 cost time 00:00:01.7471000
RotatePt_3 cost time 00:00:01.5130866