完成端口代码

小猪IOCP源码解析:完成端口实现高并发异步I/O 高并发网络编程中,阻塞线程与select模型在连接数上升后都会遭遇资源瓶颈。IOCP(完成端口)作为Windows平台的高性能异步I/O模型,通过内核完成队列将I/O事件直接分发给工作线程,线程数仅与CPU核数相关,从而支撑上万级连接。理解完成键、OVERLAPPED和缓冲池的所有权流转,是正确实现收发与避免内存错乱的关键。该模型广泛应用于游戏服务器、IM推送、实时行情等场景。本文基于小猪IOCP工程源码,讲解完成端口初始化、工作线程循环、粘包拆包、发送队列管理及优雅关闭流程,并总结了高并发环境下的典型踩坑 阅读详情
//采用完成端口的代理服务器原型代码  
http://www.vckbase.com/code/listcode.asp?mclsid=9&sclsid=901  
 
---------------------------------------------------------------  
 
http://www.vctop.com/View.Asp?ID=484&CateID=1  
---------------------------------------------------------------  
 
服务器程序:  
http://www.cnxbb.com/bcb/xbb_server_iocp.rar  
 
模拟多客户端程序  
http://www.cnxbb.com/bcb/EchoClient.rar  
---------------------------------------------------------------  
 
//  Compile:  
//  
//        cl  -o  callback  callback.cpp  ws2_32.lib  
//  
//  Command  Line  Options:  
//  
//        callback.exe    
//  
//        Note:  There  are  no  command  line  options  for  this  sample.  
 
//  
//  阻塞模式+重叠模型+完成例程机制,王天平,2003-06-20  
//  
 
#include  <winsock2.h>  
#include  <windows.h>  
#include  <stdio.h>  
 
#define  PORT  5150  
#define  DATA_BUFSIZE  8192  
 
//套接字信息数组单元结构  
typedef  struct  _SOCKET_INFORMATION  {  
     OVERLAPPED  Overlapped;//重叠结构  
     SOCKET  Socket;//套接字  
     CHAR  Buffer[DATA_BUFSIZE];//WSARecv/WSASend  数据缓冲区指针  
     WSABUF  DataBuf;//WSARecv/WSASend  数据缓冲区  
     DWORD  BytesSEND;//发送字节数  
     DWORD  BytesRECV;//接收字节数  
}  SOCKET_INFORMATION,  *  LPSOCKET_INFORMATION;  
 
void  CALLBACK  WorkerRoutine(DWORD  Error,  DWORD  BytesTransferred,  
     LPWSAOVERLAPPED  Overlapped,  DWORD  InFlags);  
 
DWORD  WINAPI  WorkerThread(LPVOID  lpParameter);  
 
SOCKET  AcceptSocket;  
 
void  main(void)  
{  
     WSADATA  wsaData;  
     SOCKET  ListenSocket;  
     SOCKADDR_IN  InternetAddr;  
     INT  Ret;  
     HANDLE  ThreadHandle;  
     DWORD  ThreadId;  
     WSAEVENT  AcceptEvent;  
 
     if  ((Ret  =  WSAStartup(0x0202,&wsaData))  !=  0)  
     {  
           printf("WSAStartup  failed  with  error  %d/n",  Ret);  
           WSACleanup();  
           return;  
     }  
 
     if  ((ListenSocket  =  WSASocket(AF_INET,  SOCK_STREAM,  0,  NULL,  0,    
           WSA_FLAG_OVERLAPPED))  ==  INVALID_SOCKET)    
     {  
           printf("Failed  to  get  a  socket  %d/n",  WSAGetLastError());  
           return;  
     }  
 
     InternetAddr.sin_family  =  AF_INET;  
     InternetAddr.sin_addr.s_addr  =  htonl(INADDR_ANY);  
     InternetAddr.sin_port  =  htons(PORT);  
 
     if  (bind(ListenSocket,  (PSOCKADDR)  &InternetAddr,  
           sizeof(InternetAddr))  ==  SOCKET_ERROR)  
     {  
           printf("bind()  failed  with  error  %d/n",  WSAGetLastError());  
           return;  
     }  
 
     if  (listen(ListenSocket,  5))  
     {  
           printf("listen()  failed  with  error  %d/n",  WSAGetLastError());  
           return;  
     }  
 
     if  ((AcceptEvent  =  WSACreateEvent())  ==  WSA_INVALID_EVENT)  
     {  
           printf("WSACreateEvent()  failed  with  error  %d/n",  WSAGetLastError());  
           return;  
     }  
 
     //  Create  a  worker  thread  to  service  completed  I/O  requests.    
 
     if  ((ThreadHandle  =  CreateThread(NULL,  0,  WorkerThread,  (LPVOID)  AcceptEvent,  0,  &ThreadId))  ==  NULL)  
     {  
           printf("CreateThread  failed  with  error  %d/n",  GetLastError());  
           return;  
     }  
 
     while(TRUE)  
     {  
           AcceptSocket  =  accept(ListenSocket,  NULL,  NULL);  
 
           if  (WSASetEvent(AcceptEvent)  ==  FALSE)  
           {  
                 printf("WSASetEvent  failed  with  error  %d/n",  WSAGetLastError());  
                 return;  
           }  
     }  
}  
 
DWORD  WINAPI  WorkerThread(LPVOID  lpParameter)  
{  
     DWORD  Flags;  
     LPSOCKET_INFORMATION  SocketInfo;  
     WSAEVENT  EventArray[1];  
     DWORD  Index;  
     DWORD  RecvBytes;  
 
     //  Save  the  accept  event  in  the  event  array.  
 
     EventArray[0]  =  (WSAEVENT)  lpParameter;  
 
     while(TRUE)  
     {  
           //  Wait  for  accept()  to  signal  an  event  and  also  process  WorkerRoutine()  returns.  
 
           while(TRUE)  
           {  
                 Index  =  WSAWaitForMultipleEvents(1,  EventArray,  FALSE,  WSA_INFINITE,  TRUE);  
 
                 if  (Index  ==  WSA_WAIT_FAILED)  
                 {  
                       printf("WSAWaitForMultipleEvents  failed  with  error  %d/n",  WSAGetLastError());  
                       return  FALSE;  
                 }  
 
                 if  (Index  !=  WAIT_IO_COMPLETION)  
                 {  
                       //  An  accept()  call  event  is  ready  -  break  the  wait  loop  
                       break;  
                 }    
           }  
 
           WSAResetEvent(EventArray[Index  -  WSA_WAIT_EVENT_0]);  
       
           //  Create  a  socket  information  structure  to  associate  with  the  accepted  socket.  
 
           if  ((SocketInfo  =  (LPSOCKET_INFORMATION)  GlobalAlloc(GPTR,  
                 sizeof(SOCKET_INFORMATION)))  ==  NULL)  
           {  
                 printf("GlobalAlloc()  failed  with  error  %d/n",  GetLastError());  
                 return  FALSE;  
           }    
 
           //  Fill  in  the  details  of  our  accepted  socket.  
 
           SocketInfo->Socket  =  AcceptSocket;  
           ZeroMemory(&(SocketInfo->Overlapped),  sizeof(WSAOVERLAPPED));      
           SocketInfo->BytesSEND  =  0;  
           SocketInfo->BytesRECV  =  0;  
           SocketInfo->DataBuf.len  =  DATA_BUFSIZE;  
           SocketInfo->DataBuf.buf  =  SocketInfo->Buffer;  
 
           Flags  =  0;  
           if  (WSARecv(SocketInfo->Socket,  &(SocketInfo->DataBuf),  1,  &RecvBytes,  &Flags,  
                 &(SocketInfo->Overlapped),  WorkerRoutine)  ==  SOCKET_ERROR)  
           {  
                 if  (WSAGetLastError()  !=  WSA_IO_PENDING)  
                 {  
                       printf("WSARecv()  failed  with  error  %d/n",  WSAGetLastError());  
                       return  FALSE;  
                 }  
           }  
 
           printf("Socket  %d  connected/n",  AcceptSocket);  
     }  
 
     return  TRUE;  
}  
 
void  CALLBACK  WorkerRoutine(DWORD  Error,  DWORD  BytesTransferred,  
     LPWSAOVERLAPPED  Overlapped,  DWORD  InFlags)  
{  
     DWORD  SendBytes,  RecvBytes;  
     DWORD  Flags;  
 
     //  Reference  the  WSAOVERLAPPED  structure  as  a  SOCKET_INFORMATION  structure  
     LPSOCKET_INFORMATION  SI  =  (LPSOCKET_INFORMATION)  Overlapped;  
 
     if  (Error  !=  0)  
     {  
         printf("I/O  operation  failed  with  error  %d/n",  Error);  
     }  
 
     if  (BytesTransferred  ==  0)  
     {  
           printf("Closing  socket  %d/n",  SI->Socket);  
     }  
 
     if  (Error  !=  0    ¦  ¦  BytesTransferred  ==  0)  
     {  
           closesocket(SI->Socket);  
           GlobalFree(SI);  
           return;  
     }  
 
     //  Check  to  see  if  the  BytesRECV  field  equals  zero.  If  this  is  so,  then  
     //  this  means  a  WSARecv  call  just  completed  so  update  the  BytesRECV  field  
     //  with  the  BytesTransferred  value  from  the  completed  WSARecv()  call.  
 
     if  (SI->BytesRECV  ==  0)  
     {  
           SI->BytesRECV  =  BytesTransferred;  
           SI->BytesSEND  =  0;  
     }  
     else  
     {  
           SI->BytesSEND  +=  BytesTransferred;  
     }  
 
     if  (SI->BytesRECV  >  SI->BytesSEND)  
     {  
 
           //  Post  another  WSASend()  request.  
           //  Since  WSASend()  is  not  gauranteed  to  send  all  of  the  bytes  requested,  
           //  continue  posting  WSASend()  calls  until  all  received  bytes  are  sent.  
 
           ZeroMemory(&(SI->Overlapped),  sizeof(WSAOVERLAPPED));  
 
           SI->DataBuf.buf  =  SI->Buffer  +  SI->BytesSEND;  
           SI->DataBuf.len  =  SI->BytesRECV  -  SI->BytesSEND;  
 
           if  (WSASend(SI->Socket,  &(SI->DataBuf),  1,  &SendBytes,  0,  
                 &(SI->Overlapped),  WorkerRoutine)  ==  SOCKET_ERROR)  
           {  
                 if  (WSAGetLastError()  !=  WSA_IO_PENDING)  
                 {  
                       printf("WSASend()  failed  with  error  %d/n",  WSAGetLastError());  
                       return;  
                 }  
           }  
     }  
     else  
     {  
           SI->BytesRECV  =  0;  
 
           //  Now  that  there  are  no  more  bytes  to  send  post  another  WSARecv()  request.  
 
           Flags  =  0;  
           ZeroMemory(&(SI->Overlapped),  sizeof(WSAOVERLAPPED));  
 
           SI->DataBuf.len  =  DATA_BUFSIZE;  
           SI->DataBuf.buf  =  SI->Buffer;  
 
           if  (WSARecv(SI->Socket,  &(SI->DataBuf),  1,  &RecvBytes,  &Flags,  
                 &(SI->Overlapped),  WorkerRoutine)  ==  SOCKET_ERROR)  
           {  
                 if  (WSAGetLastError()  !=  WSA_IO_PENDING  )  
                 {  
                       printf("WSARecv()  failed  with  error  %d/n",  WSAGetLastError());  
                       return;  
                 }  
           }  
     }  
}  
博客文章《完成端口详解》配套代码 这份代码是我博客里的文章《完成端口详解 - 手把手教你玩转网络编程系列之三》的配套代码 里面的代码包括VC++2008/VC++2010编写的完成端口服务器端的代码,还包括一个对服务器端进行压力测试的客户端,都是经过我精心调试过,并且带有非常详尽的代码注释的。当然,作为教学代码,为了能够使得代码结构清晰明了,我还是对代码有所简化,如果想要用于产品开发,最好还是需要自己再完善一下 详情请参见我的博客 http://blog.youkuaiyun.com/piggyxp 立即下载

相关推荐

完成端口IOCP示例代码

完成端口示例代码,包括用于测试的客户端代码。 是PiggyXP写的,大家可以配合PiggyXP的博客一起看 博客地址: http://blog.youkuaiyun.com/piggyxp/article/details/6922277 ps.我看了PiggyXP该资源下载得分已经超过上限,我转载不会影响PiggyXP获取下载积分,就转来赚一点积分。

完成端口模型代码

最近要做一个网络方面的小东东,基于C/S模式的。都说IOCP可以使系统达到最佳的性能,因此我就比划了两下,献丑了。抄书开始。    从本质上说,完成端口模型要求创建一个windows完成端口对象,该对象通过指定数量的线程,对重叠I/O请求进行管理,以便为已经完成的重叠I/O请求提供服务。    首先要创建一个I/O完成端口对象,用它面向任意数量的套接字句柄,管理多个I/O请求。调用以下函数创建完成

hbyh的专栏 1098

完成端口详解配套代码

小猪完成端口详解的配套代码,以及包含的服务器压力测试的简单客户端软件。

网络编程 完成端口模型

网络编程 完成端口模型

weixin_62859191的博客 1341

小猪完成端口文章及源码

《手把手叫你玩转网络编程系列之三 完成端口(Completion Port)详解》By PiggyXP(小猪) 文章内容和源码。 原文地址: http://blog.youkuaiyun.com/piggyxp/article/details/6922277

PiggyXP 完成端口的源码

作者原来的项目代码已经不能下载了,这里补上, 作者文章地址:http://blog.youkuaiyun.com/piggyxp/article/details/6922277 包含以下文件 IOCPExample_By_PiggyXP.rar PiggyStressTestClient.rar

完成端口(CompletionPort)详解 - 手把手教你玩转网络编程系列之三

手把手叫你玩转网络编程系列之三    完成端口(Completion Port)详解                                                              ----- By PiggyXP(小猪) 前 言         本系列里完成端口的代码在两年前就已经写好了,但是由于许久没有写东西了,不知该如何提笔,所以这篇文档总是在酝酿

小猪的网络编程 22万+

避坑指南:Quectel EC200A-CN在OpenWrt或嵌入式Linux下的RNDIS/ECM网络配置全解析

本文详细解析了Quectel EC200A-CN模块在OpenWrt或嵌入式Linux下的RNDIS/ECM网络配置,包括模式选择、内核配置、动态切换AT指令、网络接口生成与排错、路由与防火墙设置、性能调优及特殊场景应对策略,帮助开发者避免常见配置陷阱,提升网络稳定性和效率。

weixin_42531588的博客 286

完成端口(CompletionPort)详解

     手把手叫你玩转网络编程系列之三    完成端口(Completion Port)详解                      &...

欧特GO 1083

Windows 11下Telnet端口23连接失败的终极解决方案(附详细排查步骤)

本文详细解析了Windows 11系统中Telnet端口23连接失败的常见原因及解决方案。从Telnet客户端功能启用、服务端配置检查到网络连接诊断,提供了一套完整的排查步骤,帮助用户快速定位并解决连接问题,同时给出了安全使用Telnet的建议。

win55的博客 453

从USB相机标定到Aruco码精准定位:基于aruco-ros的机器人视觉实践

本文详细介绍了基于aruco-ros的机器人视觉实践,从USB相机标定到Aruco码精准定位的全流程。通过实战案例和优化技巧,展示了Aruco码在机器人导航中的高精度位姿识别能力,帮助开发者快速实现毫米级视觉定位系统。

weixin_27310417的博客 487

《完成端口详解》配套代码:网络编程的进阶利器

《完成端口详解》配套代码:网络编程的进阶利器 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 你是否在网络编程的道路上感到迷茫?是否对完成端口(IOCP)这一高级网络编程技术感到困惑?《完成端口详解》配套代码正是为你量身打造的进阶工具。这份代码不仅是我博客文章《完成端口详解 - 手把手教你玩转网络编程系列之三》的完美补充,更是你深入理解并掌握完成端口技术的最佳实践。 项...

gitblog_09765的博客 504

KEITHLEY 2182A + 6220/6221 系列测试系统软件

6221型与2182A型相结合,是业界最完整的差分电导测量解决方案

业余程序员小徐的博客 2986

Winsock完成端口模型-Delphi代码

 原文出处 《Windows网络编程技术》第8章 完成端口模型 由于原书附的是C代码,我把其翻译成Delphi代码。   其中winsock2.pas在delphi中不带,要另外下载http://jungla.dit.upm.es/~bti/files/winsock2.pas     program CompletionIO; {$AP

技术天地 4492

边表法

边表法是用来绘制填充一个面的,边表法的关键是边表和连接边表的扫描线。 对于边的描述利用边表数据结构,包含边与扫描线的交点x坐标,边的最大y坐标,这样可以知道边加入到哪些扫描线上,便还有一个指针来记录扫描线上其它边。 //边数据结构 #pragma once #ifndef __CAETZ__ #define __CAETZ__ #include "pch.h" #include "CPoin...

weixin_42376458的博客 2101

k8s配置habor作为镜像地址之后,如果harbor中没有镜像,如何设置自动从阿里云官方镜像仓库下载

通过 Harbor 的远端仓库可以集中管理。如果你在上游设置了 image prefix 为 library,那么对外访问 harbor.your-domain.com/library/nginx:latest 就会被 Harbor 去上游拉取 registry.cn-hangzhou.aliyuncs.com/library/nginx:latest 并缓存。- 将集群中的镜像地址改为 Harbor 的域名,比如 harbor.your-domain.com/library/nginx:latest。

极客栈 423

最简单的完成端口代码

一起来分析一下最简单的完成端口代码#include<winsock2.h>#include<windows.h>#include<stdio.h>#include<assert.h> #include"Socket5.h" voidmain(void){//变量声明WSADATAwsaData;DWORDRet;HANDLE...

weixin_34095889的博客 223

SDMA 如何实现设备对主机内存的访问

摘要:SDMA(System Direct Memory Access)是PCIe设备直接访问主机内存的核心机制,使外设无需CPU干预即可高效读写系统RAM。其实现原理包括:设备作为主控发起DMA请求,通过PCIe Memory TLP访问主机物理地址;完整通路涉及驱动分配DMA安全内存、设备配置、地址转换(IOMMU)和中断通知等步骤;关键技术涵盖地址类型(HPA/IOVA)、TLP格式、缓存一致性和安全防护机制。SDMA广泛应用于GPU、网卡、NVMe等高性能场景,是现代异构计算的基础技术,需软硬件协同

MHD0815的博客 240

完成端口的部分代码

 //完成端口的部分代码//主线程//创建原始完成端口句柄hIOCP=CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,0);if(NULL==hIOCP){ //错误处理}//创建监听套节字 ListenPort()封装了bind listen等函数SocketListen=Listen

604

history 历史命令记录功能如何防坏人(高级)

在 Linux 下面可以使用 history 命令查看用户的所有历史操作,同时 shell 命令操作记录默认保存在用户目录的 .bash_history 文件中。通过这个文件可以查询 shell 命令的执行历史,有助于运维人员进行系统审计和问题排查,同时在服务器遭受黑客攻击后,也可以查询黑客登录服务器的历史命令操作。但是黑客在入侵后,为了抹除痕迹,会删除 .bash_history 文件,这个就需...

墨痕诉清风的博客 1656

深度学习工具包 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")

使用完成端口HTTP下载的代码

使用完成端口HTTP下载的代码(转载请注明来源于金庆的专栏) 试运行asio的async_client例程时,发现CPU占用很高,所以又写了一个相同功能但直接调用完成端口API的代码,进行比较,发现同样占用CPU。与flashget比较,下载速度差不多,但flashget不占CPU。将直接API调用代码和利用asio的代码都列在下面。进行测试时,要将其中的参数定义改改,如SERVER参数。并且要找...

luliangok 114

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

初学完成端口的实例代码

////////////////////////////////////////////////////////////////////////////  完成端口//////////////////////////////////////////////////////////////////////////////#include "stdafx.h"#include #include #

程序的江湖?! 勿在浮砂筑高台! 1864

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

C#实现IOCP(完成端口)的详细代码示例

C#实现IOCP(完成端口)的详细代码如下: using System; using System.Threading; // Included for the Thread.Sleep call using Continuum.Threading; namespace Sample { //=========================================...

weixin_30657999的博客 281
上一篇: 理解I/O Completion Port
下一篇: 完成端口重叠I/O模型的服务器中,存储和管理数万个socket句柄
Garfield
博客等级 码龄26年 24粉丝 29原创
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值