WaitForSingleObject和CEvent的结合用法示例
WaitForSingleObject和CEvent的结合用法示例 VC6控制台工程 多线程控制
1、WM_TIMER消息映射 SetTimer()设置定时间隔,定时响应函数 OnTimer() 计时精度30ms,定时器消息在多任务操作系统中的优先级很低,不能得到及时响应。
2、sleep()函数 计时精度30ms,CPU占用率高,延时期间不能处理其他的消息。
3、COleDateTime类和COleDateTimeSpan类结合WINDOWS的消息处理过程 计时精度秒级。
4、GetTickCount()函数 在较短的定时中其计时误差为15ms,在较长的定时中其计时误差较低,CPU占用率高。
这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度为18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行。
5、多媒体定时器函数DWORD timeGetTime(void) 精度为ms级
6、多媒体定时器timeSetEvent()函数 精度为ms级
7、QueryPerformanceFrequency()和QueryPerformanceCounter()函数 误差不超过1微秒,精度与CPU等机器配置有关。 (现在好像都用这种方式了)
第一个函数返回PC机8253芯片的FCLK,这个值约1.19MHz,也就是说一秒钟可发出这么多的计时信号,它的倒数约840ns,这是定时器的极限精度了。 第二个函数返回定时信号个数,求差,再乘840ns,就是时间了。
例如:
// #include "mmsystem.h" // #pragma comment(lib, "winmm.lib")
LONGLONG t1,t2; LONGLONG persecond; QueryPerformanceFrequency((LARGE_INTEGER *)&persecond);//询问系统一秒钟的频率
QueryPerformanceCounter((LARGE_INTEGER *)&t1); //下面是你要计算运行时间的程序代码 ... QueryPerformanceCounter((LARGE_INTEGER *)&t2);
double time=(t2-t1)/persecond; (单位:秒)
======================================================================== QueryPerformanceCounter()这个函数返回高精确度性能计数器的值,它可以以微妙为单位计时.但是QueryPerformanceCounter()确切的精确计时的最小单位是与系统有关的,所以,必须要查询系统以得到QueryPerformanceCounter()返回的嘀哒声的频率.QueryPerformanceFrequency()提供了这个频率值,返回每秒嘀哒声的个数.计算确切的时间是从第一次调用QueryPerformanceCounter()开始的假设得到的LARGE_INTEGER 为nStartCounter,过一段时间后再次调用该函数结束的,设得到nStopCounter.两者之差除以QueryPerformanceFrequency()的频率就是开始到结束之间的秒数.由于计时函数本身要耗费很少的时间,要减去一个很少的时间开销.但一般都把这个开销忽略.公式如下: nStopCounter-nStartCounter ElapsedTime=------------------------------------ - overhead frequency
double time=(nStopCounter.QuadPart-nStartCounter.QuadPart)/frequency.Quad =================================================================================
小结:以上提到常用的9种时间函数,由于他们的用处不同,所以他们的精度也不尽相同,所以如果简单的延时可以用sleep函数,稍微准确的延时可以使用clock函数,GetTickCount函数,更高级的实用timeGetTime函数;简单的定时事件可以用Timer,准确地可以用timeSetEvent;或取一般系统时间可以通time,或者CTime,或者COleDateTime,获取准确的时间可以用clock,或者GetTickCount函数,或者timeGetTime函数,而获取准确地系统时间要使用硬件支持的QueryPerformanceFrequency函数,QueryPerformanceCounter函数。
// xztestDlg.cpp : implementation file // #include "stdafx.h" #include "xztest.h" #include "xztestDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About #include "Mmsystem.h" #ifdef UNDER_CE //WIN32_CE #pragma comment(lib, "mmtimer.lib") #else #pragma comment(lib, "Winmm.lib") #endif long m_event=0; long m_que=0; class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXztestDlg dialog CXztestDlg::CXztestDlg(CWnd* pParent /*=NULL*/) : CDialog(CXztestDlg::IDD, pParent) { //{{AFX_DATA_INIT(CXztestDlg) //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CXztestDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CXztestDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CXztestDlg, CDialog) //{{AFX_MSG_MAP(CXztestDlg) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON1, OnButton1) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CXztestDlg message handlers BOOL CXztestDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here // m_event =0; // m_que =0; m_queflag=0; UpdateData(false); return TRUE; // return TRUE unless you set the focus to a control } void CXztestDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CXztestDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this to obtain the cursor to display while the user drags // the minimized window. HCURSOR CXztestDlg::OnQueryDragIcon() { return (HCURSOR) m_hIcon; } void CXztestDlg::OnButton1() { // TODO: Add your control notification handler code here AfxBeginThread(RecSenThread,this); m_queflag=1; uTimerID=timeSetEvent(1, 1, (LPTIMECALLBACK)MilliSecondProc, (DWORD)this, TIME_PERIODIC | TIME_CALLBACK_FUNCTION); } VOID CXztestDlg::MilliSecondProc(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2) { CXztestDlg *dlg = (CXztestDlg*)dwUser; m_event++; // UpdateData(false); ::SetDlgItemInt(dlg->m_hWnd, IDC_EDIT1, m_event, TRUE); } UINT CXztestDlg::RecSenThread(void *param) { CXztestDlg *dlg = (CXztestDlg*)param; LARGE_INTEGER litmp; LONGLONG QPart1,QPart2; double dfMinus, dfFreq, dfTim; QueryPerformanceFrequency(&litmp); dfFreq = (double)litmp.QuadPart;// 获得计数器的时钟频率 QueryPerformanceCounter(&litmp); QPart1 = litmp.QuadPart;// 获得初始值 while(1) { if(1 == dlg->m_queflag) { do { QueryPerformanceCounter(&litmp); QPart2 = litmp.QuadPart;//获得中止值 dfMinus = (double)(QPart2-QPart1); dfTim = dfMinus / dfFreq;// 获得对应的时间值,单位为秒 }while(dfTim*1000<(m_que+1)); m_que++; ::SetDlgItemInt(dlg->m_hWnd, IDC_EDIT2, m_que, TRUE); } } return 0; } void CXztestDlg::OnButton2() { // TODO: Add your control notification handler code here timeKillEvent(uTimerID); m_queflag =0; }
运行图: