<html> <head> <title>阿牛测试</title> </head> <body> <script language=javascript> /* * 函数名: evlon.sleep(ms) * 作者: evlon(阿牛) MSN:niukl@msn.com QQ:273352165 * 功能: 模拟 C 语言的 Sleep * 用途: 用到时就有用了,最简单的情况就是在聊天室的服务端中, * 通过循环把Application的内容写到客户端,但这样会CPU占用率过高 * 这时把这个函数加入,会几乎不占用CPU * */ function Evlon() { this.xh = new ActiveXObject("Msxml2.ServerXMLHTTP"); this.lresolveTimeout = 0; // 解析DNS名字的超时时间 this.lconnectTimeout = 500; // 建立Winsock连接的超时时间 this.lsendTimeout = 0 ; // 发送数据的超时时间 this.lreceiveTimeout = 0 ; // 接收response的超时时间 this.xh.setTimeouts(this.lresolveTimeout,this.lconnectTimeout,this.lsendTimeout,this.lreceiveTimeout); this.urlport = "http://127.0.0.1:1111";
} Evlon.prototype.sleep = function(ms) { var beg = new Date(); var count = Math.floor(ms / 500); var lastms = ms % 500; this.xh.setTimeouts(this.lresolveTimeout,this.lconnectTimeout,this.lsendTimeout,this.lreceiveTimeout); for(var i = 0 ;i< count + 1; ++i) { //先看一下时间过了没有 var now = new Date(); if(ms < now - beg) { break; } else { if( i == count) { this.xh.setTimeouts(this.lresolveTimeout,lastms,this.lsendTimeout,this.lreceiveTimeout); } //Sleep try { this.xh.open("GET",this.urlport,false,null,null); this.xh.send(); } catch(e){ } } } } //下面是测试程序,在指定时间内观查CPU占用率 function testSleep(timeSpan /*秒*/) { try { var beg = new Date(); var evlon = new Evlon(); var nCount = 0; while(true) { var end = new Date(); var span = end - beg; if(span > timeSpan * 1000) { break; } nCount ++; evlon.sleep(200); } var end = new Date(); var span = end - beg; var msg = '共运行' + nCount.toString() + '次/n占用时间' + span + '毫秒'; alert(msg); } catch(e) { alert(e.message); } } testSleep(5); </script> </body> </html>