关于Windows下定时器的使用

windows下的定时器(获取系统时间)和linux下的定时器(获取系统时间) 一、windows下的clock(): #include <stdio.h> #include <time.h> #include <windows.h> int main() { printf("startTime:%ld\n",clock()); Sleep(50);//50ms printf("endTime:%ld\n",clock()); r... 阅读详情

在VC中,我写了不少应用级的软件,多数基于MFC来写代码。关于定时器的使用,在编码过程中,也会经常用到,现就常用的定时器作个比较,以方便大家使用。

常见的定时器有如下几种:CTimer、timeSetEvent和Socket通讯中的select

一、CTimer

CTimer的使用在MFC中最为常见,在基于CWnd的类中用起来简单、方便,缺点是必须要有窗口,可见的或不可见都可以。

使用方法如下:

1.开启定时器:

UINT SetTimer(
   UINT nIDEvent,            //定时器ID
   UINT nElapse,             //触发时间间隔,单位是毫秒。事实上,最小的的触发时间是50ms。最大的触发时间是USER_TIMER_MAXIMUM,即0x7FFFFFFF毫秒,即24.855天,如需每个月触发一次,建议自己另加一计数器,以实现更长时间的定时器
   void ( CALLBACK* lpfnTimer )(HWND, UINT, UINT, DWORD) = NULL  //一般为NULL
) throw();

2.响应定时器:

afx_msg void OnTimer(           //触发时间到后的响应函数,消息ID是WM_TIMER
   UINT_PTR nIDEvent              //定时器ID
);
3.结束定时器:
BOOL KillTimer(                      //关闭定时器
   UINT nIDEvent                      //定时器ID 
) throw();

所以,用CTimer类来实现定时器时,有二点需注意:1.要有窗口,不能应用于服务软件的开发;2.定时的时间最好不要超过一天

 

二、timeSetEvent

timeSetEvent使用在多媒体中的应用较多,实时性也较好。使用方法如下:

1.初始化

MMRESULT timeGetDevCaps(          //得到系统的时钟步长信息
  LPTIMECAPS
ptc, 
  UINT
cbtc       
);

MMRESULT timeBeginPeriod(          //设置定时器的时钟步长
  UINT
uPeriod 
);

2.启动定时器

MMRESULT timeSetEvent(
  UINT         
uDelay,                         //定时器触发时长,单位是毫秒
  UINT
           uResolution,                  //定时器的时钟步长,单位是毫秒。如有可能,这个参数的时长应尽可能地长,以减少系统开销
  LPTIMECALLBACK
lpTimeProc,        //定时器触发时间到后的回调函数
  DWORD_PTR    
dwUser,                //用户自定义参数,当回调函数被调用时,dwUser将作为参数传入
  UINT
           fuEvent                         //定时器触发方式。可以是TIME_ONESHOT(只触发一次)、TIME_PERIODIC(可多次触发)
);

3.关闭定时器

MMRESULT timeKillEvent(
  UINT
uTimerID 
);

使用timeSetEvent来实现定时器时,理论上定时的时间最长也可以是24天,但实际在应用中会发现当时钟步长为50毫秒时,设的触发时长稍长情况下,有时会有不会触发定时器现象!有二点需注意:1.可以没有窗口,能应用于服务软件的开发;2.时钟步长为50毫秒时,定时的时间最好不要超过一分钟

下面是我们已实现的由timeSetEvent写就的CTimer代码,供大家参照:

 

// Timer.h: interface for the CTimer class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_TIMER_H__DB3A5421_33F9_4FB5_A4F6_22FB017020E3__INCLUDED_)
#define AFX_TIMER_H__DB3A5421_33F9_4FB5_A4F6_22FB017020E3__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "ArrayEx.h"

class CTimer
{
public:
 DWORD m_dwTimerPeriodMax;
 struct strTimerInfo
 {
  UINT uiTimerCount,
   uiTimerIndex;
  strTimerInfo()
  {
   ZeroMemory(this, sizeof(strTimerInfo));
  }
 };
 CMapUIntToUInt m_mapEventID2TimerInfo;
 CTimer();
 virtual ~CTimer();
 UINT SetTimer(UINT nElapse);
 BOOL KillTimer(UINT &nIDEvent);
 void KillAllTimer();
 virtual void OnTimer(UINT nIDEvent);
};

#endif // !defined(AFX_TIMER_H__DB3A5421_33F9_4FB5_A4F6_22FB017020E3__INCLUDED_)

 


// Timer.cpp: implementation of the CTimer class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "Timer.h"
#include <Mmsystem.h>
#include "AutoLock.h"
#include "EventLog.h"

#pragma comment(lib, "Winmm.lib")

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CTimer::CTimer() : m_dwTimerPeriodMax(50)
{
 TIMECAPS  tc;
 if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) == TIMERR_NOERROR)
 {
  //分辨率的值不能超出系统的取值范围
  m_dwTimerPeriodMax = tc.wPeriodMax;
  //调用timeBeginPeriod函数设置定时器的分辨率,类似于for循环的步长
  timeBeginPeriod(50);
 }
}

CTimer::~CTimer()
{
 KillAllTimer();
}

void CTimer::OnTimer(UINT nIDEvent)
{
 if( m_mapEventID2TimerInfo.PLookup(nIDEvent) )
 {
  TRACE("%s CTimer::OnTimer(nIDEvent=%u)/n", COleDateTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"), nIDEvent);
  DEBUGLOG_FORMAT(("CTimer::OnTimer(nIDEvent=%u)", nIDEvent));
 }
}

void __stdcall _TimerProc(UINT uiTimerID, UINT msg, DWORD dwUser, DWORD dw1, DWORD dw2)
{
 if( dwUser )
 {
  CTimer *pTimer = (CTimer *)dwUser;
  if( TRUE )
  {
   CreateAutoLock(pTimer->m_mapEventID2TimerInfo.m_Semaphore);
   CMapUIntToUInt::CPair *pTimerInfoPair = pTimer->m_mapEventID2TimerInfo.PLookup(uiTimerID);
   if( pTimerInfoPair )
   {
    CTimer::strTimerInfo *pTimerInfo = (CTimer::strTimerInfo *)pTimerInfoPair->value;
    if( ++pTimerInfo->uiTimerIndex<pTimerInfo->uiTimerCount )
     return;
    pTimerInfo->uiTimerIndex = 0;
   }
  }
  pTimer->OnTimer(uiTimerID);
 }
}

UINT CTimer::SetTimer(UINT nElapse)
{
 UINT nIDEvent = 0;
 if( nElapse<60000 )
  nIDEvent = timeSetEvent(nElapse, 50, (LPTIMECALLBACK)_TimerProc, (DWORD)this, TIME_PERIODIC);
 else
 {
  strTimerInfo *pTimerInfo = new strTimerInfo;
  if( nElapse>300000 )
  {
   pTimerInfo->uiTimerCount = nElapse/60000;
   nIDEvent = timeSetEvent(60000, 60000, (LPTIMECALLBACK)_TimerProc, (DWORD)this, TIME_PERIODIC);
  }
  else
  {
   pTimerInfo->uiTimerCount = nElapse/1000;
   nIDEvent = timeSetEvent(1000, 1000, (LPTIMECALLBACK)_TimerProc, (DWORD)this, TIME_PERIODIC);
  }
  if( nIDEvent==0 )
   delete pTimerInfo;
  else
  {
   CreateAutoLock(m_mapEventID2TimerInfo.m_Semaphore);
   m_mapEventID2TimerInfo[nIDEvent] = (UINT)pTimerInfo;
  }
 }
 TRACE("%s CTimer::SetTimer(nIDEvent=%u, nElapse=%u)/n", COleDateTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"), nIDEvent, nElapse);
 DEBUGLOG_FORMAT(("CTimer::SetTimer(nIDEvent=%u, nElapse=%u)", nIDEvent, nElapse));
 return nIDEvent;
}

BOOL CTimer::KillTimer(UINT &nIDEvent)
{
 if( (timeKillEvent(nIDEvent)==TIMERR_NOERROR) )
 {
  CreateAutoLock(m_mapEventID2TimerInfo.m_Semaphore);
  CMapUIntToUInt::CPair *pTimerInfoPair = m_mapEventID2TimerInfo.PLookup(nIDEvent);
  if( pTimerInfoPair )
  {
   strTimerInfo *pTimerInfo = (strTimerInfo *)pTimerInfoPair->value;
   delete pTimerInfo;
   m_mapEventID2TimerInfo.RemoveKey(nIDEvent);
  }
  TRACE("%s CTimer::KillTimer(nIDEvent=%u)/n", COleDateTime::GetCurrentTime().Format("%Y-%m-%d %H:%M:%S"), nIDEvent);
  DEBUGLOG_FORMAT(("CTimer::KillTimer(nIDEvent=%u)", nIDEvent));
  nIDEvent = 0;
  return TRUE;
 }
 else
  return FALSE;
}

void CTimer::KillAllTimer()
{
 //CreateAutoLock(m_mapEventID2TimerInfo.m_Semaphore);
 UINT uiKey = 0;
 strTimerInfo *pTimerInfo = NULL;
 POSITION Pos = m_mapEventID2TimerInfo.GetStartPosition();
 while( Pos )
 {
  m_mapEventID2TimerInfo.GetNextAssoc(Pos, uiKey, (UINT &)pTimerInfo);
  KillTimer(uiKey);
 }
 m_mapEventID2TimerInfo.RemoveAll();
}
上述代码可使用于桌面应用软件、服务软件等,但使用在桌面应用软件时,如定时器触发后需调用软件资源相关时,不宜直接调用函数,应该用SendMessage或PostMessage发送消息,由资源所在线程自行加载资源,否则会导致找不到资源的情况。

 

三、Socket通讯中的select

1.初始化

int WSAStartup(
  __in          WORD wVersionRequested,
  __out         LPWSADATA lpWSAData
);
2.利用SOCKET通讯的select的等待功能,建立定时器

int select(
  __in          int nfds,
  __in_out      fd_set* readfds,
  __in_out      fd_set* writefds,
  __in_out      fd_set* exceptfds,
  __in          const struct timeval* timeout
);

3.建立新的线程,定时器的触发时长由tv决定。例示如下:
 SOCKET hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
 FD_SET fd = {1, hSocket};
 TIMEVAL tv = {10, 0};
 int i = select(0, &fd, NULL, NULL, &tv);
 closesocket(hSocket);

4.线程退出时,清理运行环境

int  WSACleanup (void);

select的使用和timeSetEvent有很相近的功效,只是需要自行建立线程,相对较麻烦。

 

上述是我个人一点见解,希望各位同仁拍砖。

(成海2010-11-22撰于上海)

Windows下定时器SetTimer以及KillTimer的用法 阅读详情

相关推荐

windows下c定时器使用

windows下c定时器使用需求解决参考 需求 由于程序使用阻塞方式计时,导致程序效率过低,使用定时器来进行计时,保证程序效率 解决 https://docs.microsoft.com/en-us/previous-versions//ms713423(v=vs.85)?redirectedfrom=MSDN MMRESULT timeSetEvent( UINT uDelay, UINT uResolution, LPTIMECALLBA

whojoe的博客 2023

timeSetEvent()函数

timeSetEvent()函数 MMRESULT timeSetEvent( UINT uDelay, UINT uResolution, LPTIMECALLBACK lpTimeProc, ...

pinkuang3943的博客 1万+

windows下C的定时器timeSetEvent使用

 MSDN里定义的函数原型如下:MMRESULT timeSetEvent( UINT uDelay,                                             UINT uResolution,                                            L

night的专栏 2546

timeSetEvent函数

该的timeSetEvent功能启动指定的定时器事件。多媒体计时器在其自己的线程中运行。事件激活后,它会调用指定的回调函数,或设置或脉冲指定的事件对象。句法C ++ MMRESULT timeSetEvent(  UINT uDelay,  UINT uResolution,  LPTIMECALLBACK lpTimeProc,  DWORD_PTR dwUser,  UIN...

a1173356881的博客 6604

如何在labwindows CVI工程中使用windows的多媒体定时器?

这里写自定义目录标题**如何在labwindows CVI工程中使用windows的多媒体定时器?** 如何在labwindows CVI工程中使用windows的多媒体定时器? 最近在学CVI,但是在网上关于这一方面的内容相对较少,有些疑问解决起来要比其他热门软件要困难一些。最近在工程中需要使用多媒体定时器,故总结了一下两个需要注意的地方: 1,主函数使用WinMain函数 2,添加mmsystem和windows头文件 下面两个函数,StarTimer和EndTimer,供大家参考,如有错误,欢迎批评指

nwpussh的博客 723

vc c语言定时器,VC++定时器的使用(Windows SDK方式)

定时器在实际编程中使用频率比较高,例如一些需要间隔一定时间自动执行的任务,如果任务执行对时间精度要求不是太苛求,使用简单的定时器就是一个较好的选择。当然,由于定时器在系统的优先级较低,有时在执行具体任务时可能会遇到一些意想不到的问题。如果这样的话,可以考虑直接使用线程或调用GetTickCount函数自己处理。对于一些简单的游戏编程,定时器完全可以胜任。本文以VC6.0为环境说明定时器的使用方法。...

weixin_39918084的博客 845

Windows编程—Windows驱动中定时器的使用

文章目录Windows编程—Windows驱动中定时器的使用前言代码简单版升级版程序效果 Windows编程—Windows驱动中定时器的使用 前言 定时器操作是应用编程中非常常见的操作,同样的在Windows内核驱动编程中也有对应的API。在Windows应用编程中使用的是SetTimer进行定时器编程,在Windows驱动开发中也有对应的API。主要用的下面3个API。 // 1.初始化定时器 VOID KeInitializeTimer( // 指向要初始化的定时器,调用者分配空间

重庆李四 2139

Windows下使用C语言创建定时器并周期和网络调试助手通信

*fuEvent:**定时器的类型,分为以下两种类型:​ TIME_ONESHOT:当经过 uDelay 时间之后,只调用一次​ TIME_PERIODC:周期执行,每经过 uDelay 时间,就调用一次**返回值:**当函数执行成功,就返回该定时器的ID,如果失败则返回NULLcomment(,)不过,在MSDN上看到, timeSetEvent 函数已经过时了,现在都在用。

qq_41854911的博客 1553

Windows定时器的使用

//本文借鉴万立中老师的一篇博客,增加了些注释,感觉是很好的sdk编程的案例之一。 #include #include #include using namespace std; int bX, bY;//记录方块移动的坐标(方块左上角坐标

异度思想 1776

VC++使用SDL定时器替代Windows窗口定时器消息(附源码)

介绍SDL开源库中SDL定时器的使用

dvlinker的技术专栏 3645

26、Windows定时器:使用与原理详解

本文详细介绍了Windows定时器的使用与原理,包括创建、修改和删除定时器的方法,并探讨了基于消息和回调函数两种使用方式。文章还分析了Windows时间机制及可能出现的时间回绕问题,讨论了WM_TIMER消息在消息队列中的优先级及其对应用程序性能的影响。此外,还介绍了性能监视器计数器作为高精度定时工具的应用场景及其实现方法。通过合理使用定时器和性能监视器计数器,开发者可以优化程序的时间处理逻辑,提高应用的响应性和精确性。

sea99的博客 174

二、Windows编程之定时器的使用:三种方法

如果您需要在整个程序执行期间都使用定时器,那么您将得从WinMain函数中或者在处理WM_CREATE消息时呼叫SetTimer,并在退出WinMain或响应WM_DESTROY消息时呼叫KillTimer。根据呼叫SetTimer时使用的参数,可以下列三种方法之一使用定时器。方法一这是最方便的一种方法,它让Windows把WM_TIMER消息发送到应用程序的正常窗口消息处理...

weixin_34015860的博客 1026

微处理器实验报告-实验四

实验四 可编程定时/计数器8253实验 一、实验要求 利用8086外接8253可编程定时/计数器,可以实现方波的产生。 二、实验目的 1、学习8086与8253的连接方法。 2、学习8253的控制方法。 3、掌握8253定时器/计数器的工作方式和编程原理

青竹小轩的博客 5112

『windows』定时器的使用

Windows系统三种定时器的分析

fallenink的专栏 1046

SpringBoot3 + OAuth2.1实战:5分钟搞定授权码模式(含完整代码)

本文详细介绍了如何在SpringBoot3环境中快速实现OAuth2.1的授权码模式,包括环境配置、核心安全实现及完整代码示例。通过Spring Security集成,开发者可以高效构建企业级安全认证系统,解决版本兼容性问题,提升开发效率。

weixin_29216353的博客 141

Keil5芯片包下载后无法识别?手把手排查教程

遇到Keil5芯片包下载后不被识别的问题别慌,常见原因包括安装路径错误或包未正确注册。通过检查Pack Installer状态和手动更新设备支持列表,轻松排查故障,确保开发环境正常运行。

weixin_35459464的博客 879

windows 定时器的使用

简单的 #include &lt;stdio.h&gt; #include &lt;windows.h&gt; #include &lt;conio.h&gt; void CALLBACK TimerOutProc(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime) { printf("定时器\n"); } int main() { M...

wanyongtai的博客 611

(ZOS-API)Matlab控制ZEMAX软件调整光学系统某镜面位姿

所用软件的版本:MatlabR2022a, Zemax OpticStudio2024R1交互扩展功能,Zemax和可以同时打开,操作会比较方便在ZEMAX软件中,调整次镜位置通常有两种方法:1.在次镜前后各添加一个坐标间断面,并修改其“偏心X”“偏心Y”等参数来调整次镜的位姿;2.或者直接在次镜属性选项中设置相关数值。这两种方法对Zernike系数的采集结果无显著影响。

ecilifurt的博客 911

Windows和Linux定时器的使用

timer 1: /*--------------------windows:----------------------------------*/ 方法1:CreateTimerQueueTimer void process_timer() { HANDLE g_Event = NULL; // 定时器句柄 HANDLE hTimer = NULL; HANDLE hTime...

时间流浪者 457

具有I2S输出的多模数字麦克风ICS-43434咪头LR引脚接地或电源WS接LRCLK

ICS-43434 是一款数字 IS 输出底部收音孔麦克风。完整的 ICS-43434 解决方案包括 MEMS 传感器、信号调理、模数转换器、抽取和抗混叠滤波器、电源管理以及行业标准的 24 位 12S 接口。12S 接口允许 ICS-43434 直接连接到数字处理器,例如 DSP 和微控制器,而无需系统中的音频编解码器。

易板 5665

【Linux命令大全】006.网络通讯之write命令(实操篇)

Linux write命令摘要 write是Linux系统中用于用户间实时通讯的命令工具,允许向其他登录用户的终端发送消息。主要功能包括: 基本使用:通过write username向指定用户发送消息,Ctrl+D结束输入 终端指定:当用户登录多个终端时,可用write username tty指定目标终端 实用技巧: 使用who查看在线用户 通过管道发送单行消息:echo "内容" | write user 支持多行消息发送和简单聊天会话。

yuhuasheng1997的博客 215

windows服务中的定时器timer的使用

<br /><br />大家在使用c#写windows服务时,网上很多例子说,使用工具箱中组件中的定时器就可以,但实际上该定时器并不管用,具体原因,微软自称是Framework的bug。<br />无论是windows窗体中timer还是组件中的timer都是继承自System.Windows.Form.Timer,并不是我们需要的System.Timers ,继承自System.Timers 的timer只有手动创建。public WindowsServiceDemo()        {        

朩冰雲的专栏 4713

ArduPilot简介

一,什么是ArduPilot? ArduPilot是一个可信的,多用途的,开源的自动驾驶系统。该系统支持了非常多的交通工具类型,包括多旋翼无人机,传统直升机,固定翼飞行器,船,潜艇,巡逻车等。源码由大型开发者社区的专家和爱好者共同开发和维护。也欢迎更多的开发者加入源码的迭代演进,最好的“打开”方式就是加入开发者团队论坛。该论坛对所有人开放,在这里可以深入感受到开发者们对ArduPilot的热爱。 论坛链接:ArduPilot Discourse 开发者指南:Welcome to the ArduPil

从0到1,突破自己 5455

windows定时器详解,如何使用windows定时器

 定时器在VC中的使用频繁,以下讨论定义器的使用方法。定时器的原型是:WINUSERAPI UINT WINAPI SetTimer ( HWND hWnd , UINT nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc);hWnd       是欲设置定时器的窗体句柄。定时时间到时,系统会向该窗体发送WM_TIMER消息。nIDEvent     定时器

David的专栏 9122

辉芒微教程第五篇《定时器0实现LED灯闪烁》

定时器定时器,一听就跟个闹钟似的,对于嵌入式定时器大部分的应用中,也的确可以这么理解,但是这只能肤浅地这么理解,实际其功能不仅仅是用来计数定时,但是对于我们这种8位单片机,这么理解就够了。

qq_41809823的博客 723

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: 基于TCP的网络通讯一段时间后出现断网问题
下一篇: 解决无法在设置线程模式后对其加以更改问题:2147549446(0x80010106)
shape2100
博客等级 码龄20年 6粉丝 8原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值