private static void MySqlDbContextTest() { var result1 = StopwatchHelper.Caculate(100, () => { using (MySqlTestDbContext db = new MySqlTestDbContext()) { //for (int i = 1; i < 4; i++) //{ // Student stu = new Student(); // stu.Age = i; // stu.Name = $"monky-{i}"; // stu.GradeId = i; // db.Add(stu); //} //var result = db.QueryOne<Student>(t => t.Name.Equals("monky-6")); //result.Name = "monky-6"; //result.Age = 6; //db.Update(t => t.Id == 109, result); //var result = db.QueryCount<Student>(t => t.Name.Contains("1")); //var result = db.QueryListPaging<Student>(3,3,t=>t.Age,t => t.Name.EndsWith("3"),true); //var grades = db.QueryList<Grade2>(t => true); var list = db.QueryList <Student>(t => t.Name.Contains("monky")); //var student = db.QueryOne<Student>(t => true); //Console.WriteLine(student.Name); } }); Console.WriteLine(); Console.WriteLine($"QueryOne 100 sec:{result1.TotalMilliseconds} ms"); }
public void Run() { using var container = CreateMigrationContainer(); var logger = container.Resolve <ILogger>(); try { foreach (var action in container.Resolve <IEnumerable <IMigrationPrepareAction> >()) { action.Execute(); } foreach (var migrationType in GetMigrationTypes()) { var handler = container.ResolveOptional( typeof(IMigrationDocumentHandler <>).MakeGenericType(migrationType)) as IMigrationDocumentHandler; if (handler?.Validate() ?? false) { logger.Information($"Migration of {migrationType.Name} has started."); var result = StopwatchHelper.StopwatchFunc(() => handler.Execute(), out var watch); logger.Information($"{result} {migrationType.Name} documents have been migrated successfully."); logger.Debug($"Total time of {migrationType.Name} migration is {watch.Elapsed}." + Environment.NewLine); } } } catch (Exception ex) { logger.Error(ex, "Migration has ended with an error."); throw; } }
public static void CompareSearches() { Random randNum = new Random(); int[] test2 = Enumerable .Repeat(0, 1000000) .Select(i => randNum.Next(-10000, 10000)) .OrderBy(i => i) .ToArray(); var time0 = StopwatchHelper.MeasureRunTime(() => { ExistsInArray.ExistsSequential(test2, test2[333]); }); Console.WriteLine("Sequential Time elapsed: " + time0); var time1 = StopwatchHelper.MeasureRunTime((Action)(() => { ExistsInArray.ExistsBinarySearch((int[])test2, (int)test2[(int)333]); })); Console.WriteLine("Binary 1 Time elapsed: " + time1); var time2 = StopwatchHelper.MeasureRunTime((Action)(() => { ExistsInArray.ExistsBinarySearch((int[])test2, (int)test2[(int)333]); })); Console.WriteLine("Binary 2 Time elapsed: " + time2); }
public void AddUpdateDeleteQueryCacheLevel2(int times) { int fromCacheTimes = 0; var timeSpan = StopwatchHelper.Caculate(times, () => { using (var db = new SqlServerTestDbContext()) { //查询单个 var stu = db.QueryOne <Student>(t => t.Id == 2); //修改单个属性 stu.Name = "test11-1"; db.Update <Student>(t => t.Id == 1, stu); var students = db.QueryList <Student>(t => true); if (db.IsFromCache) { fromCacheTimes++; } } }); Trace.WriteLine($"执行查询{times}次耗时:{timeSpan.TotalMilliseconds},有{fromCacheTimes}次从缓存中获取,有{times - fromCacheTimes}次从数据库获取"); //执行查询1000次耗时:19102.6441,有1000次从缓存中获取,有0次从数据库获取 //事实上,第一次查询单条的时候已经从数据库扫描并放在了缓存中,后续都是对二级缓存的操作以及二级缓存中查询 }
public void CaculateTimes(int times, int millisecondsTimeout) { var timespan = StopwatchHelper.Caculate(times, () => { Thread.Sleep(millisecondsTimeout); }); Assert.True(timespan > TimeSpan.FromMilliseconds(times * millisecondsTimeout)); }
public void Performance() { var timespan = StopwatchHelper.Caculate(1000000, () => { var configs = TestListConfig.Instance; }).TotalMilliseconds; Trace.WriteLine($"cost time :{timespan} milliseconds."); }
protected override void SourceModelListPageAction(List <TDomainModel> modelList) { base.SourceModelListPageAction(modelList); var watch = StopwatchHelper.StopwatchAction(() => DestinationContainer.Resolve <ISqlServerDbContext>().SaveChanges()); Logger.Debug( $"{modelList.Count.ToString()} {typeof(TDomainModel).Name} documents have been stored by SqlServer in {watch.Elapsed.ToString()}."); }
public void Performance() { var time = StopwatchHelper.Caculate(10000, () => { var result = SevenTinyConfig.Config; var result2 = ConnectionStringsConfig.Config; }); Console.WriteLine(time.TotalMilliseconds); }
public void ShouldNotStopNonExistentStopwatch() { // Act string caller = nameof(StopwatchHelperTests); string name = nameof(this.ShouldReturnMessageForStopwatchUsingProvidedPathAndMember); (string stopMessage, TimeSpan time) = StopwatchHelper.Stop(caller, name); // Assert stopMessage.ShouldBeNull(); time.TotalMilliseconds.ShouldBe(0); }
public static void Test() { var result = StopwatchHelper.Caculate(() => { for (int i = 0; i < 1000; i++) { IRedisCache redis = RedisManager.Instance; redis.Post("name", $"zhangsan"); } }); Console.WriteLine(result.TotalMilliseconds); }
public void ShouldReturnMessageForStopwatchUsingFilePathAndMember() { // Act string startMessage = StopwatchHelper.Start(); (string stopMessage, TimeSpan time) = StopwatchHelper.Stop(); // Assert startMessage.ShouldContain(nameof(this.ShouldReturnMessageForStopwatchUsingFilePathAndMember)); stopMessage.ShouldContain(nameof(this.ShouldReturnMessageForStopwatchUsingFilePathAndMember)); stopMessage.ShouldContain(time.ToString()); time.TotalMilliseconds.ShouldBeGreaterThan(0); }
public void Button_Click(object sender, RoutedEventArgs e) { var timeSpan = StopwatchHelper.MeasureRunTime(() => { for (double u = 0; u < y; u++) { for (double i = 0; i < x; i++) { double sq, re, minus, time, plus, divide, mod; Random r = new Random(); double genRand = r.Next(100000000, 999999999); var pi = Math.PI; sq = pi * genRand * genRand; re = 2 * pi * genRand; minus = sq - re; time = sq * re; plus = sq + re; divide = sq / re; mod = sq % re; } } }); MessageBoxButton buttons = MessageBoxButton.OK; MessageBox.Show(timeSpan.ToString(), "Done"); DateTime CurrentDate; CurrentDate = DateTime.Now; Microsoft.Win32.SaveFileDialog save = new Microsoft.Win32.SaveFileDialog(); save.Filter = "Text File|*.txt"; save.FileName = "PI_BENCHMARK" + "[" + x.ToString() + "]"; save.Title = "Save Benchmark Result Text File"; if (save.ShowDialog() == true) { string path = save.FileName; StreamWriter print = new StreamWriter(File.Create(path)); print.Write(CurrentDate.ToLongDateString()); print.Write(" "); print.WriteLine(CurrentDate.ToLongTimeString()); print.Write("[Value to calculate]=> "); print.WriteLine(x.ToString()); print.Write("[Result]=> "); print.WriteLine(timeSpan.ToString()); print.WriteLine(" "); print.Write(DeviceInformation("Win32_Processor")); print.Write(DeviceInformation("Win32_PhysicalMemory")); print.Dispose(); } }
public void PerformanceReportWithNoArguments(int count) { Trace.WriteLine($"#{count} 次调用:"); double time = StopwatchHelper.Caculate(count, () => { ClassB b = new ClassB(); }).TotalMilliseconds; Trace.WriteLine($"‘New’耗时 {time} milliseconds"); double time2 = StopwatchHelper.Caculate(count, () => { ClassB b = CreateObjectFactory.CreateInstance <ClassB>(); }).TotalMilliseconds; Trace.WriteLine($"‘Emit 工厂’耗时 {time2} milliseconds"); double time3 = StopwatchHelper.Caculate(count, () => { ClassB b = ExpressionCreateObject.CreateInstance <ClassB>(); }).TotalMilliseconds; Trace.WriteLine($"‘Expression’耗时 {time3} milliseconds"); double time4 = StopwatchHelper.Caculate(count, () => { ClassB b = ExpressionCreateObjectFactory.CreateInstance <ClassB>(); }).TotalMilliseconds; Trace.WriteLine($"‘Expression 工厂’耗时 {time4} milliseconds"); double time5 = StopwatchHelper.Caculate(count, () => { ClassB b = Activator.CreateInstance <ClassB>(); //ClassB b = Activator.CreateInstance(typeof(ClassB)) as ClassB; }).TotalMilliseconds; Trace.WriteLine($"‘Activator.CreateInstance’耗时 {time5} milliseconds"); /** #1000000 次调用: * ‘New’耗时 21.7474 milliseconds * ‘Emit 工厂’耗时 174.088 milliseconds * ‘Expression’耗时 42.9405 milliseconds * ‘Expression 工厂’耗时 162.548 milliseconds * ‘Activator.CreateInstance’耗时 67.3712 milliseconds * */ }
public void ShouldNotStopAlreadyStoppedStopwatch() { // Act string caller = nameof(StopwatchHelperTests); string name = nameof(this.ShouldReturnMessageForStopwatchUsingProvidedPathAndMember); StopwatchHelper.Start(caller, name); StopwatchHelper.Stop(caller, name); (string duplicateStopMessage, TimeSpan duplicateStopTime) = StopwatchHelper.Stop(caller, name); // Assert duplicateStopMessage.ShouldBeNull(); duplicateStopTime.TotalMilliseconds.ShouldBe(0); }
public void ShouldNotStartMultipleStopwatchForSameKey() { // Act string caller = nameof(StopwatchHelperTests); string name = nameof(this.ShouldReturnMessageForStopwatchUsingProvidedPathAndMember); StopwatchHelper.Start(caller, name); string duplicateStartMessage = StopwatchHelper.Start(caller, name); StopwatchHelper.Stop(caller, name); // Assert duplicateStartMessage.ShouldBeNull(); }
public void PerformanceReport(int count) { double time = StopwatchHelper.Caculate(count, () => { ClassB b = new ClassB(); }).TotalMilliseconds; Trace.WriteLine($"‘直接实例化’{count} 次调用耗时 {time} milliseconds");//‘直接实例化’1000000 次调用耗时 23.8736 milliseconds double time2 = StopwatchHelper.Caculate(count, () => { ClassB b = CreateObjectFactory.CreateInstance <ClassB>(); }).TotalMilliseconds; Trace.WriteLine($"‘工厂创建’{count} 次调用耗时 {time2} milliseconds");//‘工厂创建’1000000 次调用耗时 149.5811 milliseconds }
public void QueryListWithCacheLevel1(int times) { int fromCacheTimes = 0; var timeSpan = StopwatchHelper.Caculate(times, () => { using (var db = new SqlServerTestDbContext()) { var students = db.QueryList <Student>(t => true); if (db.IsFromCache) { fromCacheTimes++; } } }); Trace.WriteLine($"执行查询{times}次耗时:{timeSpan.TotalMilliseconds},有{fromCacheTimes}次从缓存中获取,有{times - fromCacheTimes}次从数据库获取"); //执行查询10000次耗时:1598.2349 }
public void Time_Sync_AsExpected() { // arrange var items = new[] { new[] { 1, 2 }, new[] { 1, 2 } }; // act var result = StopwatchHelper.Time(() => { items.CartesianProduct(); }); // assert result.TotalMilliseconds.ShouldBeGreaterThan(0); }
public void ShouldReturnMessageForStopwatchUsingProvidedPathAndMember() { // Act string caller = nameof(StopwatchHelperTests); string name = nameof(this.ShouldReturnMessageForStopwatchUsingProvidedPathAndMember); string startMessage = StopwatchHelper.Start(caller, name); (string stopMessage, TimeSpan time) = StopwatchHelper.Stop(caller, name); // Assert startMessage.ShouldContain(caller); startMessage.ShouldContain(name); stopMessage.ShouldContain(caller); stopMessage.ShouldContain(name); stopMessage.ShouldContain(time.ToString()); time.TotalMilliseconds.ShouldBeGreaterThan(0); }
public async Task Time_Async_AsExpected() { // arrange var file = System.IO.File.OpenRead(Assembly.GetExecutingAssembly().Location); var buff = new byte[1024]; var read = 0; // act var result = await StopwatchHelper.TimeAsync(async() => { read = await file.ReadAsync(buff, 0, buff.Length); }); // assert result.TotalMilliseconds.ShouldBeGreaterThan(0); buff.ShouldContain(x => x != 0); read.ShouldBe(buff.Length); }
public void QueryListWithCacheLevel2(int times) { int fromCacheTimes = 0; var timeSpan = StopwatchHelper.Caculate(times, () => { using (var db = new SqlServerTestDbContext()) { var students = db.QueryList <Student>(t => true); if (db.IsFromCache) { fromCacheTimes++; } } }); Trace.WriteLine($"执行查询{times}次耗时:{timeSpan.TotalMilliseconds},有{fromCacheTimes}次从缓存中获取,有{times - fromCacheTimes}次从数据库获取"); //执行查询10000次耗时:5846.0249,有9999次从缓存中获取,有1次从数据库获取。 //通过更为详细的打点得知,共有两次从数据库获取值。第一次直接按条件查询存在一级缓存,后台线程扫描表存在了二级缓存。 //缓存打点结果:二级缓存没有扫描完毕从一级缓存获取数据,二级缓存扫描完毕则都从二级缓存里面获取数据 }
public void PerformanceReportWithArguments(int count) { Trace.WriteLine($"#{count} 次调用:"); double time = StopwatchHelper.Caculate(count, () => { ClassA a = new ClassA(new ClassB()); }).TotalMilliseconds; Trace.WriteLine($"‘New’耗时 {time} milliseconds"); double time2 = StopwatchHelper.Caculate(count, () => { ClassA a = CreateObjectFactory.CreateInstance <ClassA>(new ClassB()); }).TotalMilliseconds; Trace.WriteLine($"‘Emit 工厂’耗时 {time2} milliseconds"); double time4 = StopwatchHelper.Caculate(count, () => { ClassA a = ExpressionCreateObjectFactory.CreateInstance <ClassA>(new ClassB()); }).TotalMilliseconds; Trace.WriteLine($"‘Expression 工厂’耗时 {time4} milliseconds"); double time5 = StopwatchHelper.Caculate(count, () => { ClassA a = Activator.CreateInstance(typeof(ClassA), new ClassB()) as ClassA; }).TotalMilliseconds; Trace.WriteLine($"‘Activator.CreateInstance’耗时 {time5} milliseconds"); /** #1000000 次调用: * ‘New’耗时 29.3612 milliseconds * ‘Emit 工厂’耗时 634.2714 milliseconds * ‘Expression 工厂’耗时 620.2489 milliseconds * ‘Activator.CreateInstance’耗时 588.0409 milliseconds * */ }
public void Run() { var listener = new HttpListener(); listener.Prefixes.Add("http://localhost:7667/"); listener.Start(); while (true) { try { var context = listener.GetContext(); Console.WriteLine("Started ", context.Request); var ms = StopwatchHelper.TimeInMs(() => ProcessRequest(context)); Console.WriteLine("Finished {0}ms", ms); } catch (Exception e) { Console.WriteLine(e); } } }
private static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; InputValidator.Validate(args); var mode = args[0]; var sourceFilePath = args[1]; var targetFilePath = args[2]; LogSettings.LogLevel = GetLogLevel(); if (File.Exists(targetFilePath)) { File.Delete(targetFilePath); } Console.WriteLine($"Start {mode.ToLowerInvariant()}ing file {sourceFilePath}"); var progressBar = new AnimatedBar(); using (var timer = new Timer { Interval = 500 }) { timer.Elapsed += (sender, eventArgs) => progressBar.Step(); timer.Start(); using (var pool = new WorkerPool(Math.Max(Environment.ProcessorCount * 2, 4))) { var logger = LogFactory.GetInstance().GetLogger <ConsoleLogger>(); var compressor = new GzipCompressorFactory(logger, pool).Get(mode); var time = StopwatchHelper.Time(() => compressor.Execute(sourceFilePath, targetFilePath), logger); Console.WriteLine($"{mode.ToLowerInvariant()}ing finished in {time}"); } timer.Stop(); } Console.WriteLine("Press Enter to continue"); Console.ReadLine(); }
public static void WaitForPageToLoad(string titleOfExpectedPage = "default") { using (var s = new StopwatchHelper()) { while (s.ElapsedMilliseconds <= (TimeSpan.FromMinutes(6).TotalMilliseconds)) { var title = JsExecutor.Execute("return document.title"); var readyState = JsExecutor.Execute("return document.readyState"); if (!(title.Contains(titleOfExpectedPage))) { Thread.Sleep(5000); } if (readyState != "complete") { Thread.Sleep(5000); } else if (readyState == "complete") { Thread.Sleep(3000); break; } } } }
public void Run() { Listener = new HttpListener(); Listener.Prefixes.Add(Url); Listener.Start(); while (true) { try { if (Listener == null || !Listener.IsListening) { break; } var context = Listener.GetContext(); Console.WriteLine("Started ", context.Request); var ms = StopwatchHelper.TimeInMs(() => ProcessRequest(context)); Console.WriteLine("Finished {0}ms", ms); } catch (Exception e) { Console.WriteLine(e); } } }
public static void Test() { Student5 stu5 = new Student5 { HealthLevel = 100, SchoolClass = new SchoolClass { Name = "class1" } }; var test0 = StopwatchHelper.Caculate(1000000, () => { Student stu = Mapper.AutoMapper <Student, Student5>(stu5, t => t.Name = "jony"); }); Console.WriteLine("使用反射调用 1 百万次耗时:"); Console.WriteLine(test0.TotalMilliseconds); Console.WriteLine(); var test1 = StopwatchHelper.Caculate(1000000, () => { Student stu = Mapper <Student5, Student> .AutoMapper(stu5, t => t.Name = "jony"); }); Console.WriteLine("使用Expression表达式树调用 1 百万次耗时:"); Console.WriteLine(test1.TotalMilliseconds); Console.WriteLine(); var test2 = StopwatchHelper.Caculate(1000000, () => { Student stu = new Student { HealthLevel = stu5.HealthLevel, Name = "jony" }; }); Console.WriteLine("使用代码直接构建 1 百万次耗时:"); Console.WriteLine(test2.TotalMilliseconds); //Student1 stu1 = new Student1 { Uid = Guid.NewGuid() }; //Student2 stu2 = new Student2 { Name = "jony" }; //Student3 stu3 = new Student3 { Age = 13 }; //Student4 stu4 = new Student4 { BodyHigh = 180 }; //Student5 stu5 = new Student5 { HealthLevel = 100, SchoolClass = new SchoolClass { Name = "class1" } }; //var normal = StopwatchHelper.Caculate(1000000, () => //{ // Student stu = new Student { Uid = stu1.Uid, Name = stu2.Name, Age = stu3.Age, BodyHigh = stu4.BodyHigh, HealthLevel = stu5.HealthLevel }; // // Console.WriteLine(stu.BodyHigh); //}); //Console.WriteLine($"normal used:{normal.TotalMilliseconds}"); //var expression = StopwatchHelper.Caculate(100000, () => //{ // Student stu = Mapper<Student1, Student2, Student3, Student4, Student5, Student>.AutoMapper(stu1, stu2, stu3, stu4, stu5, t => { t.Name = "333"; }); // //Console.WriteLine(SerializeObject(stu)); //}); //Console.WriteLine($"expression used:{expression.TotalMilliseconds}"); //var reflection = StopwatchHelper.Caculate(100000, () => //{ // Student stu = Mapper.AutoMapper<Student, Student1, Student2, Student3, Student4, Student5>(stu1, stu2, stu3, stu4, stu5); //}); //Console.WriteLine($"reflection used:{reflection.TotalMilliseconds}"); }
private static void BankinateCacheTest() { int i = 0; var result1 = StopwatchHelper.Caculate(100, () => { using (var db = new MySqlTestDbContext()) { Thread.Sleep(1000); i++; //Task.Run(() => //{ // db.AddAsync(new Student { Name = "jony-" + i }); //}); Console.WriteLine(i); var c1 = db.QueryCount <Student>(t => t.Name.EndsWith("1")); Console.WriteLine(db.IsFromCache); var stu = db.QueryOne <Student>(t => t.Id == 205); Console.WriteLine(db.IsFromCache); var stu2 = db.QueryOne <Student>(t => t.Id == 206); Console.WriteLine(db.IsFromCache); var stu3 = db.QueryOne <Student>(t => t.Id == 207); Console.WriteLine(db.IsFromCache); var c2 = db.QueryCount <Student>(t => t.Name.EndsWith("2")); Console.WriteLine(db.IsFromCache); //var stu4 = db.QueryOne<Student>(t => t.Id == 207); //Console.WriteLine(db.IsFromCache); //var stu5 = db.QueryList<Student>(t => t.Name.StartsWith("monk")); //Console.WriteLine(db.IsFromCache); //var stu6 = db.QueryOne<Student>(t => t.Name.Contains("m")); //Console.WriteLine(db.IsFromCache); //var c3 = db.QueryCount<Student>(t => t.Name.EndsWith("3")); //Console.WriteLine(db.IsFromCache); //var stu7 = db.QueryOne<Student>(t => t.Name.Contains("k")); //Console.WriteLine(db.IsFromCache); //var list2 = db.QueryListPaging<Student>(1, 2, t => t.GradeId, true); //Console.WriteLine("paging " + db.IsFromCache); } }); Console.WriteLine(); Console.WriteLine($"QueryOne {i} sec:{result1.TotalMilliseconds} ms"); }
public static void Reset(string name) { StopwatchHelper.GetWatch(name).Reset(); }
public static void Start(string name) { StopwatchHelper.GetWatch(name).Start(); }