Inheritance: MonoBehaviour
Example #1
1
        private static void OnBeginRequest(object sender, EventArgs e) {
            var context = (HttpApplication)sender;

            // TaskCreationOptions.PreferFairness 를 지정해야, StartNew() 메소드를 바로 시작한다.
            var stopwatchTask
                = new Task<Lazy<double>>(() => {
                                             var sw = new Stopwatch();
                                             sw.Start();

                                             if(IsDebugEnabled) {
                                                 var request = context.Request;
                                                 log.Debug(BeginRequestLogFormat,
                                                           request.UserHostAddress,
                                                           request.RequestType,
                                                           request.CurrentExecutionFilePath);
                                             }

                                             // Lazy 값을 처음 호출할 때, stop watch가 끝나고, 경과 값을 반환한다.
                                             return new Lazy<double>(() => {
                                                                         sw.Stop();
                                                                         return sw.ElapsedMilliseconds;
                                                                     });
                                         });
            stopwatchTask.Start();

            Local.Data[AsyncAccessLogModuleKey] = stopwatchTask;
        }
Example #2
1
        /// <summary>
        /// Экспортирует массив данных в XLSX формат с учетом выбранной локали
        /// </summary>
        /// <param name="path">Путь к файлу, в который нужно сохранить данные</param>
        /// <param name="localisation">Локализация</param>
        /// <returns>Успешное завершение операции</returns>
        public override bool Export(String path, Localisation localisation)
        {
            try
            {
                if (!path.EndsWith(".xlsx"))
                    path += ".xlsx";

                log.Info(String.Format("Export to .xlsx file to: {0}", path));
                var timer = new Stopwatch();
                timer.Start();
                var file = new FileInfo(path);
                using (var pck = new ExcelPackage(file))
                {
                    ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
                    ws.Cells["A1"].LoadFromDataTable(dataTable, true);
                    ws.Cells.AutoFitColumns();
                    pck.Save();
                }

                timer.Stop();
                log.Info(String.Format("Export complete! Elapsed time: {0} ms", timer.Elapsed.Milliseconds));
                return true;
            }
            catch (Exception ex)
            {
                log.Error("Can't export to .xlsx file!", ex);
                return false;
            }
        }
Example #3
1
        public static void Main()
        {
            #if DEBUG
            Console.SetIn(new System.IO.StreamReader(@"../../test.020.in.txt"));
            Debug.Listeners.Add(new ConsoleTraceListener());
            #endif

            Stopwatch sw = new Stopwatch();
            sw.Start();
            StringBuilder sb = new StringBuilder();
            int lines = int.Parse(Console.ReadLine());
            for (int i = 0; i < lines; i++)
            {
                string line = Console.ReadLine();

                bool isValid = Validate(line);
                if (isValid)
                {
                    sb.AppendLine("VALID");
                }
                else
                {
                    sb.AppendLine("INVALID");
                }
            }
            sw.Stop();
            Console.Write(sb.ToString());
            Debug.WriteLine(sw.Elapsed);
            string bla = "asdlj";
        }
Example #4
1
        public RectangleTransparent()
        {
            clearPen = new Pen(Color.FromArgb(1, 0, 0, 0));
            borderDotPen = new Pen(Color.Black, 1);
            borderDotPen2 = new Pen(Color.White, 1);
            borderDotPen2.DashPattern = new float[] { 5, 5 };
            penTimer = Stopwatch.StartNew();
            ScreenRectangle = CaptureHelpers.GetScreenBounds();

            surface = new Bitmap(ScreenRectangle.Width, ScreenRectangle.Height);
            gSurface = Graphics.FromImage(surface);
            gSurface.InterpolationMode = InterpolationMode.NearestNeighbor;
            gSurface.SmoothingMode = SmoothingMode.HighSpeed;
            gSurface.CompositingMode = CompositingMode.SourceCopy;
            gSurface.CompositingQuality = CompositingQuality.HighSpeed;
            gSurface.Clear(Color.FromArgb(1, 0, 0, 0));

            StartPosition = FormStartPosition.Manual;
            Bounds = ScreenRectangle;
            Text = "ShareX - " + Resources.RectangleTransparent_RectangleTransparent_Rectangle_capture_transparent;

            Shown += RectangleLight_Shown;
            KeyUp += RectangleLight_KeyUp;
            MouseDown += RectangleLight_MouseDown;
            MouseUp += RectangleLight_MouseUp;

            using (MemoryStream cursorStream = new MemoryStream(Resources.Crosshair))
            {
                Cursor = new Cursor(cursorStream);
            }

            timer = new Timer { Interval = 10 };
            timer.Tick += timer_Tick;
            timer.Start();
        }
        static void Main(string[] args)
        {
            ///===========================================
            ///Unzip the archive in the project directory
            ///===========================================

            Stopwatch sw = new Stopwatch();
            TrieNode start = new TrieNode();
            Dictionary<string, int> wordsInDictionary = new Dictionary<string, int>();
            var words = SetInputText();


            PopulateDictionary(sw, words, wordsInDictionary);

            //takes about 9 secs
            PopulateTrie(sw, start, words);

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine("Word: {0}", words[i].ToString());


                SearchInTrie(sw, start, words, words[i].ToString());

                SearchInDictionary(sw, wordsInDictionary, words, words[i].ToString());
            }
        }
        private static void TestArgumentNullCheckSpeed(int numberOfCalls)
        {
            var test1 = new Test1();
            var test2 = new Test2();
            var normalNullParameterCheckingTesting = new NormalNullParameterCheckingTesting();
            var stopWatch = new Stopwatch();

            stopWatch.Start();

            for (var i = 0; i < numberOfCalls; i++)
            {
                normalNullParameterCheckingTesting.TestWith1(test1);
            }

            Console.WriteLine("Normal null checking speed with 1 Test parameter: " + stopWatch.ElapsedMilliseconds);

            stopWatch.Restart();

            for (var i = 0; i < numberOfCalls; i++)
            {
                normalNullParameterCheckingTesting.TestWith2(test1, test2);
            }

            Console.WriteLine("Normal null checking speed with 2 Test parameter: " + stopWatch.ElapsedMilliseconds);
        }
Example #7
0
        public static void DoStuff(ProgramOptions options)
        {
            Options = options;
            GlobalStopwatch = Stopwatch.StartNew();

            DumpSettings(Options);

            if (!Options.ShowTitles && Options.ShouldLog)
            {
                foreach (var output in Outputs)
                {
                    ConsoleExtensions.WriteLineColor(output.OutputColor, output.Name);
                }
            }

            Iterations = Options.NumberOfIterations;
            for (var i = 1; i <= Iterations; i++)
            {
                ConsoleExtensions.WriteLine($"Iteration {i}".ToUpper());

                foreach (var increment in Increments)
                {
                    RunIncrement(increment);
                }
            }
            GlobalStopwatch.Stop();
            if (Options.ShouldOutput) WriteOutputs(DateTime.UtcNow);
            if (Options.ShouldHaltOnEnd) ConsoleExtensions.WriteLine("DONE");
            if (Options.ShouldHaltOnEnd) Console.ReadLine();
        }
        public DashboardView()
        {
            InitializeComponent();

            AndonManager = new AndonManager(StationList, null, Andonmanager.AndonManager.MODE.MASTER);

            AndonManager.start();
            StationList = new Queue<int>();

            Plans = new Plans();
            PlanGrid.DataContext = Plans;

            Actuals = new Models.Actuals();
            ActualGrid.DataContext = Actuals;

            AppTimer = new Timer(1000);
            AppTimer.AutoReset = false;
            AppTimer.Elapsed += AppTimer_Elapsed;

            EfficiencyWatch = new Stopwatch();

            using (PSBContext DBContext = new PSBContext())
            {

                Shifts = DBContext.Shifts.ToList();

                foreach (Shift s in Shifts)
                {
                    s.Update();
                }

            }

            AppTimer.Start();
        }
        public void when_sending_message_with_session_then_session_receiver_gets_both_messages_fast()
        {
            var sender = this.Settings.CreateTopicClient(this.Topic);
            var signal = new AutoResetEvent(false);
            var body1 = Guid.NewGuid().ToString();
            var body2 = Guid.NewGuid().ToString();
            var stopWatch = new Stopwatch();

            var receiver = new SessionSubscriptionReceiver(this.Settings, this.Topic, this.Subscription);

            sender.Send(new BrokeredMessage(body1) { SessionId = "foo" });
            sender.Send(new BrokeredMessage(body2) { SessionId = "bar" });

            var received = new ConcurrentBag<string>();

            receiver.Start(
                m =>
                {
                    received.Add(m.GetBody<string>());
                    signal.Set();
                    return MessageReleaseAction.CompleteMessage;
                });

            signal.WaitOne();
            stopWatch.Start();
            signal.WaitOne();
            stopWatch.Stop();

            receiver.Stop();

            Assert.Contains(body1, received);
            Assert.Contains(body2, received);
            Assert.InRange(stopWatch.Elapsed, TimeSpan.Zero, TimeSpan.FromSeconds(2));
        }
        public void PerformanceListByTeam_With10000BunniesRandomlyDistributedIn5000RoomsInSameTeam()
        {
            //Arrange
            var roomsCount = 5000;
            var bunniesCount = 10000;
            for (int i = 0; i < roomsCount; i++)
            {
                this.BunnyWarCollection.AddRoom(i);
            }
            for (int i = 0; i < bunniesCount; i++)
            {
                this.BunnyWarCollection.AddBunny(i.ToString(), 2, this.Random.Next(0, roomsCount));
            }

            //Act
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for (int i = 0; i < 10000; i++)
            {
                var result = this.BunnyWarCollection.ListBunniesByTeam(2).Count();
                Assert.AreEqual(10000, result, "Incorrect count of bunnies returned by List By Team Command!");
            }
            timer.Stop();
            Assert.IsTrue(timer.ElapsedMilliseconds < 100);
        }
Example #11
0
 public void Build()
 {
     _stateHash.Clear();
       Stopwatch sw = new Stopwatch();
       sw.Start();
       var i1 = sw.ElapsedMilliseconds;
       Data = _language.ParserData;
       CheckPrecedenceSettings(_language.GrammarData, Data.ParseMethod);
       var i2 = sw.ElapsedMilliseconds;
       var i3 = sw.ElapsedMilliseconds;
       CreateLalrParserStates();
       var i4 = sw.ElapsedMilliseconds;
       //TODO: move all the following to a single method
       //ComputeTransitionIncludesAndItemLookbacks();  //5 ms
       var i5 = sw.ElapsedMilliseconds;
       PropagateTransitionsIncludes(0);               //220 ms
       var i6 = sw.ElapsedMilliseconds;
       //ComputeTransitionsSources(0);
       var i7 = sw.ElapsedMilliseconds;
       ComputeLookaheads();
       var i8 = sw.ElapsedMilliseconds;
       var i9 = sw.ElapsedMilliseconds;
       ComputeAndResolveConflicts();
       var i10 = sw.ElapsedMilliseconds;
       var i11 = sw.ElapsedMilliseconds;
       var i12 = sw.ElapsedMilliseconds;
       if (Data.ParseMethod == ParseMethod.Nlalr) {
     SwitchConflictingStatesToNonCanonicalLookaheads();
       }
       var i13 = sw.ElapsedMilliseconds;
       ReportAndSetDefaultActionsForConflicts();
       CreateReduceActions();
       ComputeStateExpectedLists();
 }
Example #12
0
        static void Main(string[] args)
        {
            var sw = new Stopwatch();
            sw.Start();
            try
            {
                var options = new Options();

                if (CommandLine.Parser.Default.ParseArguments(args, options))
                {
                    var processor = new Processor();

                    if (options.SiteAnalysisMode)
                    {
                        processor.AnalyzeWebSites(options).Wait();
                    }
                    else
                    {
                        processor.AnalyzeWebPages(options).Wait();
                    }
                }
            }
            catch (AggregateException ex)
            {
                foreach (var exception in ex.InnerExceptions)
                {
                    Console.Error.WriteLine(exception.Message);
                }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }
Example #13
0
    public BXSSMainWindow()
    {
        _settings = new BXSSSettings();
        _settings.Load();
        _screenshot = new Screenshot(
            KSPUtil.ApplicationRootPath + "PluginData/BXSS/",
            () =>
                {
                    _prevUIState = Visible;
                    Visible = false;
                    if(_mainUIEnabled)
                        RenderingManager.ShowUI(false);
                },
            () =>
                {
                    Visible = _prevUIState;
                    if(_mainUIEnabled)
                        RenderingManager.ShowUI(true);
                });

        _collapsed = true;
        _mainUIEnabled = true;
        _autoIntervalEnabled = false;

        _autoIntervalStopwatch = new Stopwatch();

        WindowPosition = _settings.WindowPosition;

        Caption = "B.X.S.S";

        SetupControls();
    }
Example #14
0
 public void ComputeTimesPrimes()
 {
     Stopwatch w = new Stopwatch();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers1(100000);
     Console.WriteLine("Primes 1: " + w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Reset();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers2(100000);
     Console.WriteLine("Primes 2: "+ w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Reset();
     w.Start();
     PrimeNumbers.GeneratePrimeNumbers3(100000);
     Console.WriteLine("Primes 3: " + w.ElapsedMilliseconds.ToString());
     w.Stop();
     w.Start();
     for (int i = 1; i <= 100000; i++)
     {
         int mod = i % 2;
     }
     w.Stop();
     Console.WriteLine("Primes 4: " + w.ElapsedMilliseconds.ToString());
 }
        public CastSpellAction()
        {
            _spamControl = new Stopwatch();
            QueueIsRunning = false;
            Properties["Casted"] = new MetaProp("Casted", typeof(int), new ReadOnlyAttribute(true));
            Properties["SpellName"] = new MetaProp("SpellName", typeof(string), new ReadOnlyAttribute(true));
            Properties["Repeat"] = new MetaProp("Repeat", typeof(DynamicProperty<int>),
                new TypeConverterAttribute(typeof(DynamicProperty<int>.DynamivExpressionConverter)));
            Properties["Entry"] = new MetaProp("Entry", typeof(uint));
            Properties["CastOnItem"] = new MetaProp("CastOnItem", typeof(bool), new DisplayNameAttribute("Cast on Item"));
            Properties["ItemType"] = new MetaProp("ItemType", typeof(InventoryType), new DisplayNameAttribute("Item Type"));
            Properties["ItemId"] = new MetaProp("ItemId", typeof(uint));
            Properties["RepeatType"] = new MetaProp("RepeatType", typeof(RepeatCalculationType), new DisplayNameAttribute("Repeat Type"));
            // Properties["Recipe"] = new MetaProp("Recipe", typeof(Recipe), new TypeConverterAttribute(typeof(RecipeConverter)));

            Casted = 0;
            Repeat = new DynamicProperty<int>(this,"1");
            RegisterDynamicProperty("Repeat");
            Entry = 0u;
            RepeatType = RepeatCalculationType.Craftable;
            Recipe = null;
            CastOnItem = false;
            ItemType = InventoryType.Chest;
            ItemId = 0u;
            Properties["SpellName"].Value = SpellName;

            //Properties["Recipe"].Show = false;
            Properties["ItemType"].Show = false;
            Properties["ItemId"].Show = false;
            Properties["Casted"].PropertyChanged += OnCounterChanged;
            CheckTradeskillList();
            Properties["RepeatType"].PropertyChanged += CastSpellActionPropertyChanged;
            Properties["Entry"].PropertyChanged += OnEntryChanged;
            Properties["CastOnItem"].PropertyChanged += CastOnItemChanged;
        }
Example #16
0
        private static void Main(string[] args)
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            arguments = new Arguments(Environment.CommandLine);

            try
            {
                GenerateAll();

                if (compiler.Templates.Count > 0)
                {
                    Console.WriteLine("Running Compiler...");
                    compiler.Run();
                    Console.WriteLine("Writing Files...");
                    foreach (Template template in compiler.Templates)
                        using (StreamWriter sw = File.CreateText(template.OutputPath))
                            sw.Write(template.FinalCode);

                    Console.WriteLine("Done!");
                }
            }
            catch (Exception x)
            {
                Console.WriteLine("Error Message: {0}", x);
                Console.ReadKey();
            }
            timer.Stop();
            Console.WriteLine("Execution Time: " + timer.ElapsedMilliseconds + "ms");
        }
Example #17
0
        private string Measure(int a_bytes, Action a_action)
        {
            Stopwatch sw = new Stopwatch();

            int repeats = 0;

            a_action();

            for (; ; )
            {
                HighPriority();

                try
                {
                    sw.Start();
                    a_action();
                    sw.Stop();
                }
                finally
                {
                    NormalPriority();
                }

                repeats++;

                if (sw.ElapsedMilliseconds > MEASURE_TIME)
                    if (repeats > MIN_REPEATS)
                        break;
            }

            double mbs = a_bytes / 1024.0 / 1024.0 * repeats;
            double seconds = sw.ElapsedMilliseconds / 1000.0;

            return String.Format((mbs / seconds).ToString("F2"));
        }
Example #18
0
        private static void Main(string[] args)
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.BelowNormal;

            //XTrace.Log = new NetworkLog();
            XTrace.UseConsole();
#if DEBUG
            XTrace.Debug = true;
#endif
            while (true)
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
#if !DEBUG
                try
                {
#endif
                    Test2();
#if !DEBUG
                }
                catch (Exception ex)
                {
                    XTrace.WriteException(ex);
                }
#endif

                sw.Stop();
                Console.WriteLine("OK! 耗时 {0}", sw.Elapsed);
                ConsoleKeyInfo key = Console.ReadKey(true);
                if (key.Key != ConsoleKey.C) break;
            }
        }
Example #19
0
        static void Main(string[] args)
        {
            Stopwatch stopper = new Stopwatch();
            stopper.Start();
            int i = 0;
            int numbers = 2;

            while (i < 1000)
            {
                if (isprime(numbers))
                {
                    primes[i]=numbers;
                    i++;
                }
                numbers++;
            }
            int a, b, c, d; a = b = c = d = 0;
            int n = 0;
            for (n = 120; true; ++n)
            {

                a=dpf(n);
                b=dpf(n+1);
                c=dpf(n+2);
                d=dpf(n+3);
                if ((a == b) && (b == c) && (c == d) && (d == 4))
                    break;
            }
            stopper.Stop();
            Console.WriteLine("The numers are {0} {1} {2} {3} ", n, n+1, n+2, n+3);
            Console.WriteLine("Elapsed time {0} ms", stopper.ElapsedMilliseconds);
        }
Example #20
0
		///<summary>Select All EHRMeasures from combination of db, static data, and complex calculations.</summary>
		public static List<EhrMeasure> SelectAllMu2(DateTime dateStart,DateTime dateEnd,long provNum) {
			if(RemotingClient.RemotingRole==RemotingRole.ClientWeb) {
				return Meth.GetObject<List<EhrMeasure>>(MethodBase.GetCurrentMethod(),dateStart,dateEnd,provNum);
			}
			List<EhrMeasure> retVal=GetMU2List();
			Stopwatch s=new Stopwatch();
			for(int i=0;i<retVal.Count;i++) {
				s.Restart();
				retVal[i].Objective=GetObjectiveMu2(retVal[i].MeasureType);
				retVal[i].Measure=GetMeasureMu2(retVal[i].MeasureType);
				retVal[i].PercentThreshold=GetThresholdMu2(retVal[i].MeasureType);
				DataTable table=GetTableMu2(retVal[i].MeasureType,dateStart,dateEnd,provNum);
				if(table==null) {
					retVal[i].Numerator=-1;
					retVal[i].Denominator=-1;
				}
				else {
					retVal[i].Numerator=CalcNumerator(table);
					retVal[i].Denominator=table.Rows.Count;
				}
				retVal[i].NumeratorExplain=GetNumeratorExplainMu2(retVal[i].MeasureType);
				retVal[i].DenominatorExplain=GetDenominatorExplainMu2(retVal[i].MeasureType);
				retVal[i].ExclusionExplain=GetExclusionExplainMu2(retVal[i].MeasureType);
				retVal[i].ExclusionCount=GetExclusionCountMu2(retVal[i].MeasureType,dateStart,dateEnd,provNum);
				retVal[i].ExclusionCountDescript=GetExclusionCountDescriptMu2(retVal[i].MeasureType);
				s.Stop();
				retVal[i].ElapsedTime=s.Elapsed;
			}
			return retVal;
		}
        private static void Main()
        {
            // Testing different type of reverse algorithms
            Stopwatch timeTest = new Stopwatch();

            Console.Write("Enter some string: ");
            string str = Console.ReadLine();

            // Using StringBuilder
            timeTest.Start();
            string reversed = ReverseSB(str);
            timeTest.Stop();
            Console.WriteLine("Reverse text: {0}\ntime: {1} - StringBuilder class", reversed, timeTest.Elapsed);
            timeTest.Reset();

            Console.WriteLine();

            // Using Array.Reverse
            timeTest.Start();
            string reversedArrayReverse = ReverseArray(str);
            timeTest.Stop();
            Console.WriteLine("Reverse text: {0}\ntime: {1} - Array.Reverse", reversedArrayReverse, timeTest.Elapsed);
            timeTest.Reset();

            Console.WriteLine();

            // Using XOR
            timeTest.Start();
            string reversedXor = ReverseXor(str);
            timeTest.Stop();
            Console.WriteLine("Reverse text: {0}\ntime: {1} - XOR", reversedXor, timeTest.Elapsed);
            timeTest.Reset();
        }
Example #22
0
        /// <summary>
        /// Starts the nodelet.
        /// </summary>
        /// <param name="options">The nodelet command options.</param>
        public void Start(Options options)
        {
            using (var context = ZmqContext.Create())
            using (var client = context.CreateSocket(SocketType.REQ))
            {
                var endpoint = string.Format("tcp://{0}", options.SocketConnection);
                Console.WriteLine("Connecting to: {0}", endpoint);
                client.Connect(endpoint);

                var sw = new Stopwatch();

                foreach(var i in Enumerable.Range(1, NumberOfMessages))
                {
                    Console.WriteLine("Message {0} of {1} sent", i, NumberOfMessages);
                    var message = DateTime.UtcNow.Ticks.ToString();

                    sw.Restart();

                    client.Send(message, Encoding.Unicode);
                    var reply = client.Receive(Encoding.Unicode);

                    sw.Stop();

                    var messageIsMatch = message == reply ? 1 : 0;
                    Console.WriteLine("{0}: Reply received in {1}ms", messageIsMatch, sw.ElapsedMilliseconds);
                }

            }
        }
 Task IEventProcessor.OpenAsync(PartitionContext context)
 {
     Console.WriteLine("SimpleEventProcessor initialized.  Partition: '{0}', Offset: '{1}'", context.Lease.PartitionId, context.Lease.Offset);
     this.checkpointStopWatch = new Stopwatch();
     this.checkpointStopWatch.Start();
     return Task.FromResult<object>(null);
 }
Example #24
0
        public void InsertALot()
        {
            int n = 100000;
            var q =	from i in Enumerable.Range(1, n)
                    select new TestObj() {
                Text = "I am"
            };
            var objs = q.ToArray();
            var db = new TestDb(Path.GetTempFileName());
            db.Trace = false;

            var sw = new Stopwatch();
            sw.Start();

            var numIn = db.InsertAll(objs);

            sw.Stop();

            Assert.AreEqual(numIn, n, "Num inserted must = num objects");

            var inObjs = db.CreateCommand("select * from TestObj").ExecuteQuery<TestObj>().ToArray();

            for (var i = 0; i < inObjs.Length; i++) {
                Assert.AreEqual(i+1, objs[i].Id);
                Assert.AreEqual(i+1, inObjs[i].Id);
                Assert.AreEqual("I am", inObjs[i].Text);
            }

            var numCount = db.CreateCommand("select count(*) from TestObj").ExecuteScalar<int>();

            Assert.AreEqual(numCount, n, "Num counted must = num objects");
        }
Example #25
0
        /// <summary>
        /// Add token message at header to using NHibernate cache
        /// </summary>
        /// <param name="request"></param>
        /// <param name="channel"></param>
        /// <returns></returns>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            // add trace log for debug and performance tuning
            if (null != (request.Headers).MessageId && (request.Headers).MessageId.IsGuid)
            {
                ServiceStopWatch = Stopwatch.StartNew();
                Guid messageId;
                (request.Headers).MessageId.TryGetGuid(out messageId);

                CurrentTraceInfo = new TraceInfo()
                {
                    SessionId = (HttpContext.Current != null && HttpContext.Current.Session != null) ? HttpContext.Current.Session.SessionID : "",
                    TraceType = TraceType.WcfActionClientCall,
                    TraceName = request.Headers.Action,
                    TraceUniqueId = messageId.ToString()
                };

                TraceLogger.Instance.TraceServiceStart(CurrentTraceInfo, true);

                // Add a message header with sessionid
                MessageHeader<string> messageHeader = new MessageHeader<string>(CurrentTraceInfo.SessionId);
                MessageHeader untyped = messageHeader.GetUntypedHeader("sessionid", "ns");
                request.Headers.Add(untyped);
            }
            return null;
        }
Example #26
0
        public AgentsModule()
            : base("/agents")
        {
            Before += ctx =>
            {
                _sw = new Stopwatch();
                _sw.Start();

                return null;
            };

            After += ctx =>
                         {
                             _sw.Stop();
                             _logger.Trace("{0} [{1} ms] {2}", ctx.Request.Method, _sw.Elapsed.TotalMilliseconds, ctx.Request.Url.ToString());
                         };

            Get["/"] = parameters =>
            {
                try
                {
                    return View["Agents", new {Time = DateTime.UtcNow}];
                }
                catch (Exception e)
                {
                    _logger.WarnException(e.Message, e);
                    return null;
                }
            };
        }
      public double Insert(User user, Stopwatch stopwatch)
      {
         double execTime;
         using (SqlConnection sqlConnection = new SqlConnection(connectionString))
         {
            sqlConnection.Open();
            using (SqlCommand command = new SqlCommand())
            {
               command.Connection = sqlConnection;
               command.CommandType = CommandType.Text;
               command.CommandText = "INSERT INTO [dbo].[User] (Id, FirstName, DateAdded, LastName, Age, DepartmentId) VALUES (@id, @firstN, @dateAdd, @lastN, @ag, @depId)";
               command.Parameters.AddWithValue("@id", user.Id);
               command.Parameters.AddWithValue("@firstN", user.FirstName);
               command.Parameters.AddWithValue("@dateAdd", user.DateAdded);
               command.Parameters.AddWithValue("@lastN", user.LastName);
               command.Parameters.AddWithValue("@ag", user.Age);
               command.Parameters.AddWithValue("@depId", user.DepartmentId);

               stopwatch.Restart();
               command.ExecuteNonQuery();
               stopwatch.Stop();
               execTime = ((double)stopwatch.ElapsedTicks / (double)System.Diagnostics.Stopwatch.Frequency) * 1000;
            }
            sqlConnection.Close();
         }
         return execTime;
      }
Example #28
0
    public static void Main()
    {
        Stopwatch watch = new Stopwatch();
        Random rand = new Random();
        watch.Start();
        for (int i = 0; i < iterations; i++)
            DayOfYear1(rand.Next(1, 13), rand.Next(1, 29));
        watch.Stop();
        Console.WriteLine("Local array: " + watch.Elapsed);
        watch.Reset();
        watch.Start();
        for (int i = 0; i < iterations; i++)
            DayOfYear2(rand.Next(1, 13), rand.Next(1, 29));
        watch.Stop();
        Console.WriteLine("Static array: " + watch.Elapsed);

        // trying to modify static int []
        daysCumulativeDays[0] = 18;
        foreach (int days in daysCumulativeDays)
        {
            Console.Write("{0}, ", days);
        }
        Console.WriteLine("");

        // MY_STR_CONST = "NOT CONST";
    }
Example #29
0
        public static IList<TextChange> BuildChangeList(string oldText, string newText, int maxMilliseconds) {
            List<TextChange> changes = new List<TextChange>();
            var sw = new Stopwatch();
            sw.Start();

            // Simple witespace/nowhitespace tokenization and comparison
            int oldIndex = 0;
            int newIndex = 0;

            while (true) {
                bool thereIsMore = NextChunk(oldText, ref oldIndex, newText, ref newIndex, changes);
                if (!thereIsMore)
                    break;

                thereIsMore = NextChunk(oldText, ref oldIndex, newText, ref newIndex, changes);
                if (!thereIsMore)
                    break;

                if (sw.ElapsedMilliseconds > maxMilliseconds) {
                    return null; // time's up
                }
            }

            return changes;
        }
Example #30
0
        /*
            GNOME cache -> 	00:00:05.6705334 (creating cache)
                    00:00:00.2680794.(once cached)

            With no cache -> 00:00:28.8975945 (using Pixbuf)
        */
        static void Main()
        {
            string[] files;
            Provider provider = Factory.Provider;
            Pixbuf buf;
            TimeSpan time;
            int nulls = 0;

            files = Directory.GetFiles ("/home/jordi/Desktop/berna"); // Directory with images to test

            Stopwatch stopWatch = new Stopwatch ();
            stopWatch.Start ();
            foreach (string file in files)
            {
                buf = provider.GetThumbnail (file, 96, 96);

                if (buf == null) {
                    nulls++;
                    buf = new Pixbuf (file);
                }

                buf.Dispose ();
            }

            stopWatch.Stop ();
            time = stopWatch.Elapsed;

            Console.WriteLine ("Time needed {0}. Total files {1}, thumbnailed {2}, skipped {3}", time, files.Length, files.Length - nulls, nulls);
            return;
        }