先看一段实现图像灰度化的代码:
private void button4_Click(object sender, EventArgs e)
{
if (curBitmap != null)
{
double time1, time2;
time1 = Microsoft.VisualBasic.DateAndTime.Timer;
Rectangle rect = new Rectangle(0, 0, curBitmap.Width, curBitmap.Height);
//以可读写方式锁定全部位图像素
System.Drawing.Imaging.BitmapData bmpData = curBitmap.LockBits(rect,
System.Drawing.Imaging.ImageLockMode.ReadWrite, curBitmap.PixelFormat);
byte temp = 0;
//启动不安全模式
unsafe
{
//得到首地址
byte* ptr = (byte*)(bmpData.Scan0);
//二维图像循环
for (int i = 0; i < bmpData.Height; i++)
{
for (int j = 0; j < bmpData.Width; j++)
{
temp = (byte)(0.299 * ptr[2] + 0.587 * ptr[1] + 0.114 * ptr[0]);
ptr[0] = ptr[1] = ptr[2] = temp;
//指向下一个像素
ptr += 3;
}
//指向下一行数组的首个字母
ptr += bmpData.Stride - bmpData.Width * 3;
}
}
curBitmap.UnlockBits(bmpData);
Invalidate();
time2 = Microsoft.VisualBasic.DateAndTime.Timer;
this.toolStripStatusLabel1.Text = "耗时:"+ Convert.ToString(time2 - time1) + "s!";
}
}
这里是使用了Microsoft.visualBasic中的timer。除此之外,还有几种可以用于计时的计时器,
下面列出C#中的其它几种计时器:
1.System.Timers.Timer和System.Windows.Forms.Timer,它的最低识别为1/18s.
2.timeGetTime,它的最低识别为5ms.
3.System.EnvironmentCount,它的最低识别为毫秒级.
4.win32API包含了一种精度较高的计时器,通常用于时间精度要求较高的环境,如游戏开发。