Example #1
0
        private static void Sort(ISortable sortable, IGeneratorItems generatorItems, int amount, FileService fileService)
        {
            fileService.Save(path, sortable.ToString());

            Console.WriteLine("---- Analyze " + amount + " ----" + sortable.ToString());
            TimeWatch timer = new TimeWatch();

            timer.Start();
            List <int> list = generatorItems.GetData(amount);

            Console.WriteLine("Time Loading List: " + timer.GetEllapsedMilliSeconds());

            timer.Restart();
            List <int> listOrderAsc  = new List <int>(list);
            List <int> listOrderDesc = new List <int>(list);

            Console.WriteLine("Time Loading List to Order Asc or Desc:" + timer.GetEllapsedMilliSeconds());

            timer.Restart();
            List <int> orderedList = OrderAsc(sortable, listOrderAsc);
            long       timeAsc     = timer.GetEllapsedMilliSeconds();

            Console.WriteLine("Time Ordering Asc:" + timer.GetEllapsedMilliSeconds());

            timer.Restart();
            List <int> orderedDescList = OrderDesc(sortable, listOrderDesc);
            long       timeDesc        = timer.GetEllapsedMilliSeconds();

            Console.WriteLine("Time Ordering Desc:" + timer.GetEllapsedMilliSeconds());

            fileService.Save(path, Environment.NewLine + $"Amount:{amount},TimeAsc:{timeAsc}, TimeDesc:{timeDesc}");
        }
Example #2
0
        public ButtonPlay(float x, float y, float radius, string text) : base(x, y, radius, text)
        {
            Paint1 = new SKPaint
            {
                Style       = SKPaintStyle.Stroke,
                IsAntialias = true,
                StrokeWidth = 7,
                Color       = new SKColor(180, 100, 0, 150)
            };

            Paint2 = new SKPaint
            {
                Style       = SKPaintStyle.Fill,
                IsAntialias = true,
                StrokeWidth = 7,
                Color       = new SKColor(180, 100, 0, 150)
            };

            Timer       = new TimeWatch();
            Timer.Tick += tick => { Radius += (float)Math.Cos(tick / 10.0f); };

            MouseUp += (element, state) =>
            {
                Timer.Start(1, 45);
            };
        }
Example #3
0
        private void OnCompleted()
        {
            if (System.Threading.Interlocked.CompareExchange(ref mCompletedStatus, 1, 0) == 0)
            {
                Time = TimeWatch.GetElapsedMilliseconds() - mStartTime;
                mClient.Client.ClientError = null;
                mClient.Client.DataReceive = null;
                try
                {
                    taskCompletionSource.SetResult(this);
                }

                finally
                {
                    if (mClient.Client.IsConnected)
                    {
                        PipeStream pipeStream = mClient.Client.Stream.ToPipeStream();
                        if (pipeStream.Length > 0)
                        {
                            pipeStream.ReadFree((int)pipeStream.Length);
                        }
                    }
                }
            }
        }
Example #4
0
        public void Execute()
        {
            double time = TimeWatch.GetTotalSeconds() - mLastTime;

            mLastTime = TimeWatch.GetTotalSeconds();
            int value = (int)((double)(mCount - mLastCount) / time);

            mLastCount = mCount;
            Rps        = value;

            SendIOPer   = (long)((double)(mSendIO - mLastSendIO) / time);
            mLastSendIO = mSendIO;

            SendBytesPer   = (long)((double)(mSendBytes - mLastSendBytes) / time);
            mLastSendBytes = mSendBytes;

            ReceiveIOPer   = (long)((double)(mReceiveIO - mLastReceiveIO) / time);
            mLastReceiveIO = mReceiveIO;

            ReceiveBytesPer   = (long)((double)(mReceiveBytes - mLastReceiveBytes) / time);
            mLastReceiveBytes = mReceiveBytes;

            if (value > MaxRps)
            {
                MaxRps = value;
            }
            AvgRps = (int)(mCount / (TimeWatch.GetTotalSeconds() - mFirstTime));
        }
Example #5
0
        private bool OnCompleted()
        {
            if (Status == LoaderStatus.Completed)
            {
                return(true);
            }
            var completed = false;
            var count     = System.Threading.Interlocked.Increment(ref mTotalRequest);

            if (Setting.Type == "time")
            {
                var time = TimeWatch.GetTotalSeconds();
                if (time - mStartTime > Setting.Value)
                {
                    completed = true;
                }
            }
            else
            {
                completed = count > Setting.Value;
            }
            if (completed)
            {
                this.Status = LoaderStatus.Completed;
            }
            return(completed);
        }
Example #6
0
 public void Start(float timeSeconds)
 {
     TimeWatch.Stop();
     Model.finishTime = timeSeconds;
     TimeWatch.Start();
     StartedSubject.OnNext(Unit.Default);
 }
Example #7
0
        internal HttpRequest CreateRequest(ISession session)
        {
            HttpToken token = (HttpToken)session.Tag;

            token.Request.RequestTime = TimeWatch.GetTotalMilliseconds();
            return(token.Request);
        }
Example #8
0
 public RequestAgent(TcpClientAgent clientAgent, ServerAgent serverAgent, HttpRequest request, HttpResponse response,
                     UrlRouteServerGroup.UrlServerInfo urlServerInfo, Routes.UrlRoute urlRoute)
 {
     mTransferEncoding = false;
     mRequestLength    = 0;
     Code         = 0;
     Server       = serverAgent;
     Request      = request;
     Response     = response;
     mClientAgent = clientAgent;
     mClientAgent.Client.ClientError = OnSocketError;
     mClientAgent.Client.DataReceive = OnReveive;
     mBuffer       = mClientAgent.Buffer;
     Status        = RequestStatus.None;
     UrlServerInfo = urlServerInfo;
     UrlRoute      = urlRoute;
     mStartTime    = TimeWatch.GetElapsedMilliseconds();
     mRequestID    = request.ID;
     //System.Threading.Interlocked.Increment(ref RequestCount);
     //mHistoryRequests[mRequestID] = this;
     if (UrlRoute.TimeOut > 0)
     {
         TimerOutValue = mStartTime + UrlRoute.TimeOut;
         UrlRoute.Gateway.TimeoutFactory.Add(this);
     }
     mProxyStream = new PipeStream(UrlRoute.Gateway.ProxyBufferPool);
 }
Example #9
0
 public bool ValidateRPS()
 {
     lock (this)
     {
         long now = TimeWatch.GetElapsedMilliseconds();
         ActiveTime = now;
         if (mEnbaledTime > now)
         {
             return(false);
         }
         if (mServer.Options.IPRpsLimit == 0)
         {
             return(true);
         }
         if (now - mLastTime >= 1000)
         {
             mLastTime = now;
             mRPS      = 0;
             return(true);
         }
         else
         {
             mRPS++;
             bool result = mRPS < mServer.Options.IPRpsLimit;
             if (!result)
             {
                 mEnbaledTime = mServer.Options.IPRpsLimitDisableTime + now;
             }
             return(result);
         }
     }
 }
Example #10
0
        public IList List(Type type, Command cmd, Region region)
        {
            TimeWatch.________________________________________________________("Peanut->Execute SQL Return List");
            if (region == null)
            {
                region = new Region {
                    Start = 0, Size = 99999999
                }
            }
            ;
            IList items = null;

            if (Mappings.ObjectMapper.CurrentOM.SelectChange != null)
            {
                Mappings.ObjectMapper.CurrentOM.SelectChange.Change(cmd);
            }
            System.Type itemstype = System.Type.GetType("System.Collections.Generic.List`1");
            itemstype = itemstype.MakeGenericType(type);
            if (region.Size > DBContext.DefaultListMaxSize)
            {
                items = (IList)Activator.CreateInstance(itemstype, DBContext.DefaultListMaxSize);
            }
            else
            {
                items = (IList)Activator.CreateInstance(itemstype, region.Size);
            }
            object item = null;

            using (IDataReader reader = ExecuteReader(cmd))
            {
                int index = 0;
                while (reader.Read())
                {
                    if (index >= region.Start)
                    {
                        item = Activator.CreateInstance(type);

                        if (item is IEntityState)
                        {
                            ((IEntityState)item).ConnectionType = this.Type;
                            ((IEntityState)item).LoadData(reader);
                        }
                        else
                        {
                            Mappings.ObjectMapper.CurrentSelectReader.ReaderToObject(reader, item);
                        }
                        items.Add(item);
                        if (items.Count == region.Size)
                        {
                            cmd.DbCommand.Cancel();
                            reader.Close();
                            break;
                        }
                    }
                    index++;
                }
            }
            TimeWatch.________________________________________________________();
            return(items);
        }
Example #11
0
 private void OnTimeOut(object state)
 {
     mTimer.Change(-1, -1);
     try
     {
         for (int i = 0; i < awaiterManager.AwaiterTables.Count; i++)
         {
             var items = awaiterManager.AwaiterTables[i].TimeOut(TimeWatch.GetElapsedMilliseconds());
             if (items.Count > 0)
             {
                 for (int k = 0; k < items.Count; k++)
                 {
                     ThrowBlockException(items[k].ID, $"{items[k].ID} process timeout!");
                 }
             }
         }
     }
     catch (Exception e_)
     {
         OnError(null, TIMEOUT_PROCESS_ERROR, "TimeOut handler error", e_);
     }
     finally
     {
         mTimer.Change(1000, 1000);
     }
 }
Example #12
0
        public static void Test()
        {
            TimeWatch.Clean();
            TimeWatch.________________________________________________________("Peaunt Exeuctes");

            CustOrderHist coh = new CustOrderHist();

            coh.CustomerID = "ANATR";
            IList <CustOrderHistItem> cohs = coh.List <CustOrderHistItem>();

            foreach (CustOrderHistItem item in cohs)
            {
                Console.WriteLine(item.ProductName);
            }


            SQL      sql;
            Employee employee = (Employee.employeeID == 3).ListFirst <Employee>(DB.DB3);

            Console.WriteLine(employee);
            TimeWatch.________________________________________________________("Insert Employee");
            sql = "insert into employees(firstname,lastname) values(@p1,@p2)";
            sql["p1", "henry"]["p2", "fan"].Execute();
            TimeWatch.________________________________________________________();

            TimeWatch.________________________________________________________("del employee");
            sql = "delete from employees where firstname=@p1";
            sql["p1", "henry"].Execute();
            TimeWatch.________________________________________________________();

            TimeWatch.________________________________________________________("count employee");
            Query <int> getCount = "select count(*) from employees";

            TimeWatch.________________________________________________________();

            TimeWatch.________________________________________________________("get employee");
            Query <Employee> getEmp = "select * from employees where employeeid=3";

            TimeWatch.________________________________________________________();


            TimeWatch.________________________________________________________("list employee");
            Query <IList <Employee> > getEmps = "select * from employees";

            TimeWatch.________________________________________________________();

            TimeWatch.________________________________________________________("del employee with expression");
            (Employee.firstName == "henry").Delete <Employee>();
            TimeWatch.________________________________________________________();

            TimeWatch.________________________________________________________("modify employee");
            (Employee.employeeID == 3).Edit <Employee>(d => { d.LastName = "a"; });
            TimeWatch.________________________________________________________();

            ListOrders();

            TimeWatch.________________________________________________________();

            TimeWatch.Report(o => { Console.WriteLine(o.ToString()); });
        }
Example #13
0
        public async void Ping()
        {
            if (System.Threading.Interlocked.CompareExchange(ref mPingStatus, 1, 0) == 0)
            {
                if (TcpClient.IsConnected)
                {
                    try
                    {
                        RPCPacket request = new RPCPacket();
                        request.Url = "/__System/Ping";
                        var response = await XRPCClient.SendWait(request, TcpClient, null);

                        PingTime = TimeWatch.GetElapsedMilliseconds();
                    }
                    catch (Exception e_)
                    {
                    }
                    finally
                    {
                        if (TimeOut(XRPCClient.PingTimeout * 1000))
                        {
                            TcpClient.DisConnect();
                            bool isnew;
                            TcpClient.Connect(out isnew);
                        }
                    }
                }
                else
                {
                    PingTime = TimeWatch.GetElapsedMilliseconds();
                }
                System.Threading.Interlocked.Exchange(ref mPingStatus, 0);
            }
        }
Example #14
0
        public int ExecuteNonQuery(Command cmd)
        {
            TimeWatch.________________________________________________________("Peanut->Execute NonQuery");
            int value = mHandler.ExecuteNonQuery(cmd);

            TimeWatch.________________________________________________________();
            return(value);
        }
Example #15
0
        public IDataReader ExecuteReader(Command cmd)
        {
            TimeWatch.________________________________________________________("Peanut->Execute Reader");
            IDataReader result = mHandler.ExecuteReader(cmd);

            TimeWatch.________________________________________________________();
            return(result);
        }
Example #16
0
        public object ExecuteScalar(Command cmd)
        {
            TimeWatch.________________________________________________________("Peanut->Execute Scalar");
            object result = mHandler.ExecuteScalar(cmd);

            TimeWatch.________________________________________________________();
            return(result);
        }
Example #17
0
        public static void Set(string key, object data, double seconds = 60)
        {
            CacheItem item = new CacheItem();

            item.Data       = data;
            item.ActiveTime = TimeWatch.GetTotalSeconds() + seconds;
            mCache[key]     = item;
        }
Example #18
0
        public object ExecProc(object parameter)
        {
            TimeWatch.________________________________________________________("Peanut->Execute Proce Return Object");
            object result = mHandler.ExecProc(parameter);

            TimeWatch.________________________________________________________();
            return(result);
        }
Example #19
0
        public void Add(long time)
        {
            long value = System.Threading.Interlocked.Increment(ref mCount);

            if (value == 1)
            {
                mFirstTime = TimeWatch.GetTotalSeconds();
                mLastTime  = mFirstTime;
            }
            if (time <= 5)
            {
                System.Threading.Interlocked.Increment(ref ms5);
            }
            else if (time <= 10)
            {
                System.Threading.Interlocked.Increment(ref ms10);
            }
            else if (time <= 20)
            {
                System.Threading.Interlocked.Increment(ref ms20);
            }
            else if (time <= 50)
            {
                System.Threading.Interlocked.Increment(ref ms50);
            }
            else if (time <= 100)
            {
                System.Threading.Interlocked.Increment(ref ms100);
            }
            else if (time <= 200)
            {
                System.Threading.Interlocked.Increment(ref ms200);
            }
            else if (time <= 500)
            {
                System.Threading.Interlocked.Increment(ref ms500);
            }
            else if (time <= 1000)
            {
                System.Threading.Interlocked.Increment(ref ms1000);
            }
            else if (time <= 2000)
            {
                System.Threading.Interlocked.Increment(ref ms2000);
            }
            else if (time <= 5000)
            {
                System.Threading.Interlocked.Increment(ref ms5000);
            }
            else if (time <= 10000)
            {
                System.Threading.Interlocked.Increment(ref ms10000);
            }
            else
            {
                System.Threading.Interlocked.Increment(ref msOther);
            }
        }
Example #20
0
        public void TestIsHiRes_DoesNotThrowException()
        {
            var watch = new Mock<StopwatchWrapper>();
            watch.Setup(m => m.IsHighResolution).Returns(true);

            TimeWatch sut = null;
            Assert.DoesNotThrow(() => { sut = new TimeWatch(watch.Object); });
            Assert.IsNotNull(sut);
        }
Example #21
0
 public Timer()
 {
     Model              = new TimerModel();
     StartedSubject     = new Subject <Unit>();
     StoppedTimeSubject = new Subject <float>();
     PausedTimeSubject  = new Subject <float>();
     ResumedSubject     = new Subject <Unit>();
     TimeWatch          = new TimeWatch();
 }
Example #22
0
        public void TestIsNotHiRes_ThrowsException()
        {
            var watch = new Mock<StopwatchWrapper>();
            watch.Setup(m => m.IsHighResolution).Returns(false);

            TimeWatch sut = null;
            Assert.Throws<NotSupportedException>(() => { sut = new TimeWatch(watch.Object); });
            Assert.IsNull(sut);
        }
Example #23
0
 internal void OnCompleted(EventResponseErrorArgs error)
 {
     if (System.Threading.Interlocked.CompareExchange(ref mCompletedStatus, 1, 0) == 0)
     {
         this.ResponseError = error;
         Time = (long)(TimeWatch.GetTotalMilliseconds() - Request.RequestTime);
         mClientAgent.Client.ClientError = null;
         mClientAgent.Client.DataReceive = null;
         mClientAgent.Status             = TcpClientAgentStatus.ResponseSuccess;
         //System.Threading.Interlocked.Decrement(ref RequestCount);
         //mHistoryRequests.Remove(mRequestID, out RequestAgent value);
         try
         {
             if (Code >= 500)
             {
                 if (Request.Server.EnableLog(BeetleX.EventArgs.LogType.Warring))
                 {
                     Request.Server.Log(BeetleX.EventArgs.LogType.Warring, $"gateway {Request.ID} {Request.RemoteIPAddress} {Request.Method} {Request.Url} -> {Server.Host}:{Server.Port} completed code {Code} use time:{Time}ms");
                 }
             }
             else
             {
                 if (Request.Server.EnableLog(BeetleX.EventArgs.LogType.Info))
                 {
                     Request.Server.Log(BeetleX.EventArgs.LogType.Info, $"gateway {Request.ID} {Request.RemoteIPAddress} {Request.Method} {Request.Url} -> {Server.Host}:{Server.Port} completed code {Code} use time:{Time}ms");
                 }
             }
             if (UrlRoute.Pluginer.RequestedEnabled)
             {
                 UrlRoute.Pluginer.Requested(this.GetEventRequestCompletedArgs());
             }
             Completed?.Invoke(this);
         }
         catch (Exception e_)
         {
             if (Request.Server.EnableLog(BeetleX.EventArgs.LogType.Error))
             {
                 Request.Server.Log(BeetleX.EventArgs.LogType.Error, $"gateway {Request.ID} {Request.RemoteIPAddress} {Request.Method} {Request.Url} -> {Server.Host}:{Server.Port} completed event error {e_.Message}@{e_.StackTrace}");
             }
         }
         finally
         {
             Request.ClearStream();
             if (error != null)
             {
                 Server.Gateway.OnResponseError(error);
             }
             else
             {
                 Request.Recovery();
             }
             FlushProxyStream(true);
             Server.Push(mClientAgent);
         }
     }
 }
Example #24
0
 public static object Get(string key)
 {
     if (mCache.TryGetValue(key, out CacheItem item))
     {
         if (TimeWatch.GetTotalSeconds() > item.ActiveTime)
         {
             return(null);
         }
         return(item.Data);
     }
     return(null);
 }
Example #25
0
        public void TestIsRunning()
        {
            var sut = new TimeWatch();

            Assert.IsFalse(sut.IsRunning);

            sut.Start();
            Assert.IsTrue(sut.IsRunning);

            sut.Stop();
            Assert.IsFalse(sut.IsRunning);
        }
Example #26
0
        private void SendMessage(AsyncTcpClient client)
        {
            ClientToken token = (ClientToken)client.Token;

            token.RequestTime = TimeWatch.GetElapsedMilliseconds();
            token.MessageIndex++;
            int index = (int)(token.MessageIndex % Messages.Count);
            var msg   = Messages[index];
            var data  = msg.ToBytes();

            client.Send(s => s.Write(data, 0, data.Length));
            this.CodeStatistics.Send(data.Length);
        }
Example #27
0
 public Request(HttpTcpClient clientAgent)
 {
     mTransferEncoding = false;
     mRequestLength    = 0;
     Code    = 0;
     mClient = clientAgent;
     mClient.Client.ClientError = OnSocketError;
     mClient.Client.DataReceive = OnReveive;
     mBuffer    = mClient.Buffer;
     Status     = RequestStatus.None;
     mStartTime = TimeWatch.GetElapsedMilliseconds();
     mRequestID = System.Threading.Interlocked.Increment(ref mRequestIDSqueue);
 }
Example #28
0
 public ConnectionContext(string connnectionString, IDriver driver, string connName)
 {
     TimeWatch.Start("Peanut->Create IConnection Context");
     mDB      = connName;
     mHandler = DBContext.CurrentHandler(connName);
     if (mHandler == null)
     {
         mHandler          = DBContext.AddConnectionHandler(connName, driver);
         mActiveConnection = true;
     }
     ConnectionName = connName;
     TimeWatch.End();
 }
Example #29
0
 public ConnectionContext(string db, IDriver driver, DB type)
 {
     TimeWatch.________________________________________________________("Peanut->Create IConnection Context");
     mDB      = db;
     mHandler = DBContext.CurrentHandler(db);
     if (mHandler == null)
     {
         mHandler          = DBContext.AddConnectionHandler(mDB, driver);
         mActiveConnection = true;
     }
     Type = type;
     TimeWatch.________________________________________________________();
 }
Example #30
0
        public bool ValidateRPS()
        {
            if (MaxRPS == 0)
            {
                return(true);
            }
            long now = TimeWatch.GetElapsedMilliseconds();

            if (now - mLastTime >= 1000)
            {
                return(true);
            }
            return(mRPS < MaxRPS);
        }
Example #31
0
        internal IList List(Type type, IConnectinContext cc, Region region)
        {
            TimeWatch.________________________________________________________("Peanut->SQL to list");
            System.Type itemstype = System.Type.GetType("System.Collections.Generic.List`1");
            itemstype = itemstype.MakeGenericType(type);
            IList result;

            if (region == null)
            {
                region = new Region(0, 99999999);
            }
            if (region.Size > DBContext.DefaultListMaxSize)
            {
                result = (IList)Activator.CreateInstance(itemstype, DBContext.DefaultListMaxSize);
            }
            else
            {
                result = (IList)Activator.CreateInstance(itemstype, region.Size);
            }
            Mappings.CommandReader cr = Mappings.CommandReader.GetReader(mBaseSql, type);
            int     index             = 0;
            Command cmd = GetCommand();

            TimeWatch.________________________________________________________("Peanut->DataReader to list");
            using (IDataReader reader = cc.ExecuteReader(cmd))
            {
                TimeWatch.________________________________________________________("Peanut->Read Data");
                while (reader.Read())
                {
                    if (index >= region.Start)
                    {
                        object item = Activator.CreateInstance(type);
                        cr.ReaderToObject(reader, item);
                        result.Add(item);
                        if (result.Count >= region.Size)
                        {
                            cmd.DbCommand.Cancel();
                            reader.Dispose();
                            break;
                        }
                    }
                    index++;
                }
                TimeWatch.________________________________________________________();
            }
            TimeWatch.________________________________________________________();
            TimeWatch.________________________________________________________();
            return(result);
        }
Example #32
0
        private static void ListOrders()
        {
            TimeWatch.________________________________________________________("list order");
            TimeWatch.________________________________________________________("create table");
            JoinTable table = Order.employeeID.InnerJoin(Employee.employeeID)
                              .InnerJoin(Order.customerID, Customer.customerID)
                              .Select(Order.orderID.At(), Customer.companyName, Employee.firstName, Employee.lastName);

            TimeWatch.________________________________________________________();
            TimeWatch.________________________________________________________("List");
            IList <OrderView> orders = new Expression().List <OrderView>(table);

            TimeWatch.________________________________________________________();
            TimeWatch.________________________________________________________();
        }
Example #33
0
        public TimeStatisticsData GetData()
        {
            double now  = TimeWatch.GetTotalSeconds();
            double time = now - mLastTime;

            if (time > 1)
            {
                mData.Count   = mCount;
                this.Increase = (double)(mCount - mLastCount);
                mData.Rps     = (int)(Increase / (time));
                mLastTime     = now;
                mLastCount    = mCount;
            }
            return(mData);
        }