CogStopwatch简单使用
目录
前言
对检测来说,往往要统计运算时间,下面来了解一下VisionPro带有的CogStopwatch类的使用
一、准备工作
1. 准备一个窗体程序,添加引用。引用添加之前文章有。
2.窗体布局
思路是点击开启后,开始计时,每点击统计一次,计数点击统计按钮间隔时间,当关闭时计算总时间。
二、代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Cognex.VisionPro;
namespace CogStopWatchTest
{
public partial class Form1 : Form
{
CogStopwatch stopwatch = new CogStopwatch();
bool IsOpen;
double sumTime;
public Form1()
{
InitializeComponent();
IsOpen = false;
sumTime = 0;
}
private void btn_IsOpenTime_Click(object sender, EventArgs e)
{
if (IsOpen)
{
btn_IsOpenTime.Text = "计时开启";
btn_IsOpenTime.BackColor = Color.Green;
//结束计数
stopwatch.Stop();
//关闭后统计总时间
btn_OneTime_Click(sender, e);
textBox2.Text = sumTime.ToString()+"ms";
}
else
{
btn_IsOpenTime.Text = "计时关闭";
btn_IsOpenTime.BackColor = Color.Red;
//开启计数
stopwatch.Start();
//清空
textBox1.Text = "";
textBox2.Text = "";
}
IsOpen = !IsOpen;
}
private void btn_OneTime_Click(object sender, EventArgs e)
{
textBox1.Text += stopwatch.Milliseconds.ToString()+"ms"+"\t\n";
//累计
sumTime += stopwatch.Milliseconds;
//清零
stopwatch.Reset();
}
}
}
三、效果
总结
利用例子,可以了解CogStopwatch的使用,通过CogStopwatch就可以算出检测时的时间、CT等。C#也有一个类似的类System.Diagnostics.Stopwatch,具体使用看个人习惯。