private static void TestSwimInWater(CodeTimer codeTimer, Random rand) { SwimInWater instance = new SwimInWater(); instance.Solution2( JsonConvert.DeserializeObject <int[][]>( "[[0,1,2,3,4],[24,23,22,21,5],[12,13,14,15,16],[11,17,18,19,20],[10,9,8,7,6]]"), true); //16 instance.Solution2( JsonConvert.DeserializeObject <int[][]>( "[[7,34,16,12,15,0],[10,26,4,30,1,20],[28,27,33,35,3,8],[29,9,13,14,11,32],[31,21,23,24,19,18],[22,6,17,5,2,25]]"), true); //26 instance.Solution2(JsonConvert.DeserializeObject <int[][]>( "[[52,19,24,3,45,21,56,27,5],[48,35,53,12,11,75,65,61,59],[58,9,76,28,4,80,72,34,78],[63,79,33,16,64,51,13,67,23],[31,57,54,60,74,8,6,38,44],[7,77,36,37,10,2,42,68,46],[32,25,17,26,15,14,29,70,39],[50,40,49,71,0,22,55,41,73],[69,66,1,47,20,43,30,62,18]]")); Console.ReadKey(true); int testCount = 10, martixLen = 20; codeTimer.Time(1, () => { instance.Solution2(null); }); for (int i = 0; i < testCount; i++) { var len = rand.Next(martixLen) + 2; var arr = new int[len][]; var source = Enumerable.Range(0, len * len).ToList(); for (int j = 0; j < len; j++) { arr[j] = new int[len]; for (int k = 0; k < len; k++) { var randIndex = rand.Next(source.Count); arr[j][k] = source[randIndex]; source.RemoveAt(randIndex); } } int res = 0; var codeTimerResult = codeTimer.Time(1, () => { res = instance.Solution(arr); }); ShowResult.ShowMulti(new Dictionary <string, object>() { //{nameof(arr),ShowList.GetStr(arr)}, { nameof(arr), arr }, { nameof(res), res }, { nameof(codeTimerResult), codeTimerResult } }); } }
public static long Run() { long ran = 0; const int Iterations = 1; // 100 * 1000 * 1000; var toFill = new byte[12]; int[] values = { 100000, 9544, int.MaxValue - 1000 }; CodeTimer.Time(true, "fixed", Iterations, () => { for (int i = 0; i < values.Length; i++) { WriteFixed((uint)values[i], toFill, i * 4); } }); CodeTimer.Time(true, "managed", Iterations, () => { for (int i = 0; i < values.Length; i++) { WriteDirect((uint)values[i], toFill, i * 4); } }); return(ran); }
public void ThrowSystemExceptionTest() { const int calCount = 1000000; const int calMin = 100; const int step = 10; CodeTimer.Time("Devide non zero with Exception dealing ", calCount, calMin, step, () => { int i = 100, j = 1; DevideZeroException (i, j); }); CodeTimer.Time("Devide non zero with Prejudge", calCount, calMin, step, () => { int i = 100, j = 1; DevideZeroException(i, j); }); CodeTimer.Time("Devide zero with Exception dealing", calCount, calMin, step, () => { int i = 100, j = 0; DevideZeroException(i, j); }); CodeTimer.Time("Devide zero with Exception Prejudge", calCount, calMin, step, () => { const int i = 100; const int j = 0; DevideZero(i, j); }); }
public void DynamicInvokeTest2() { CodeTimer.Time("DynamicInvokeTest.Create", CreateTimes, () => { dynamic a = new InvokeMethod(); }); dynamic b = new InvokeMethod(); CodeTimer.Time("DynamicInvokeTest", InvokeTimes, () => b.Do(InvokeTimes)); }
/// <summary>计时,并用控制台输出行</summary> /// <param name="title">标题</param> /// <param name="times">次数</param> /// <param name="action">需要计时的委托</param> /// <param name="needTimeOne">是否需要预热</param> public static void TimeLine(String title, Int32 times, Action<Int32> action, Boolean needTimeOne = true) { var n = Encoding.Default.GetByteCount(title); Console.Write("{0}{1}:", n >= 16 ? "" : new String(' ', 16 - n), title); var timer = new CodeTimer(); timer.Times = times; timer.Action = action; timer.ShowProgress = true; #if !Android var currentForeColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Int32 left = Console.CursorLeft; #endif if (needTimeOne) timer.TimeOne(); timer.Time(); // 等一会,让进度那边先输出 Thread.Sleep(10); #if !Android Console.CursorLeft = left; #endif Console.WriteLine(timer.ToString()); #if !Android Console.ForegroundColor = currentForeColor; #endif }
static void Main(string[] args) { var fileName = "source4compress.txt"; var str = File.ReadAllText(fileName); Console.WriteLine("SourceFileSize\t" + str.Length.ToString("N0")); var snappybin = SnappyCompress(str); var lz4bin = LZ4Compress(str); var gzipbin = GZipCompress(str); var zstdbin = ZstdCompress(str, false, true); #region codetimer 测试代码性能 CodeTimer.Initialize(); var count = 100; CodeTimer.Time("SnappyCompress\t" + snappybin.Length.ToString("N0"), count, () => { SnappyCompress(str); }); CodeTimer.Time("LZ4Compress\t" + lz4bin.Length.ToString("N0"), count, () => { LZ4Compress(str); }); CodeTimer.Time("ZstdCompress\t" + zstdbin.Length.ToString("N0"), count, () => { ZstdCompress(str, false, true); }); CodeTimer.Time("GZipCompress\t" + gzipbin.Length.ToString("N0"), count, () => { GZipCompress(str); }); CodeTimer.Time("SnappyUnCompress", count, () => { SnappyUnCompress(snappybin); }); CodeTimer.Time("LZ4UnCompress", count, () => { LZ4UnCompress(lz4bin); }); CodeTimer.Time("ZstdUnCompress", count, () => { ZstdUnCompress(zstdbin); }); CodeTimer.Time("GZipUnCompress", count, () => { GZipUnCompress(gzipbin); }); #endregion Console.Read(); }
public override Task OnCommand(string cmd) { var msgArgs = cmd.Split(new[] { ",", ";", " " }, StringSplitOptions.RemoveEmptyEntries); int repeat = 1, thread = 1; if (msgArgs.Length > 1) { repeat = msgArgs[1].CastTo(1); } if (msgArgs.Length > 2) { thread = msgArgs[2].CastTo(1); } var message = msgArgs[0]; Task.Run(async() => { var result = await CodeTimer.Time("netty", repeat, async() => { var data = message.Encode(); await _channel.WriteAndFlushAsync(data); }, thread); Console.WriteLine(result.ToString()); }); return(base.OnCommand(cmd)); }
public override void When() { foreach (var item in Mappers) { CodeTimer.Time(item.Metadata.Category + "->" + item.Metadata.Name, 100000, () => item.Value.Map()); } }
public void ClosurePerformanceTest() { var o = new Closure(); var r = new Random((int)DateTime.Now.ToBinary()); var iteration = 100; o.Sample = new List <int>(iteration); for (int i = 0; i < iteration; i++) { o.Sample.Add(r.Next(0, 1024)); } //准备一个有1k元素的集合,遍历,测试闭包性能 Parallel.For(0, 1024, i => o.Content.Add(i)); CodeTimer.Initialize(); CodeTimer.Time("闭包方式测试", 100000, 100, 10, (samples) => { samples.UseClosure(); return(string.Empty); }, o); //o.UseClosure() CodeTimer.Time("迭代方式测试", 100000, 100, 10, (samples) => { samples.NoClosure(); return(string.Empty); }, o); }
static void MeasureExpressionCachingBenefits() { const int iterations = 10000; IQueryable <TestClass> seq = Enumerable.Range(1, 100).Select(x => new TestClass { A = x % 2 == 0, B = x * 2, C = x.ToString() }).AsQueryable(); IQueryable <string> found = null; CodeTimer.Time("create expressions each time", iterations, () => { found = seq.Where(x => x.B > 20 && x.A).Select(x => x.C); }); Expression <Func <TestClass, bool> > whereClause = x => x.B > 20 && x.A; Expression <Func <TestClass, string> > selectClause = x => x.C; CodeTimer.Time("cache expressions", iterations, () => { found = seq.Where(whereClause).Select(selectClause); }); Console.WriteLine(found); }
public void DeserializerProtoBuf() { var s = _container.Resolve <IProtoBufferSerializer>(); CodeTimer.Time("Protobuf", 10000, () => { SSOToken token = new SSOToken(); token.token = Guid.NewGuid().ToString(); token.custcode = "C001"; token.timeout = DateTime.Now; token.userid = 1; var arry = s.ToByteArray(token); }); CodeTimer.Time("Json.net", 10000, () => { SSOToken token = new SSOToken(); token.token = Guid.NewGuid().ToString(); token.custcode = "C001"; token.timeout = DateTime.Now; token.userid = 1; JsonConvert.SerializeObject(token); }); var d = _container.Resolve <IProtoBufferDeserializer>(); //var _token = d.FromByteArray<SSOToken>(arry); var str = ""; }
public static long Run() { long ran = 0; const int Iterations = 2000000000; // 100 * 1000 * 1000; CodeTimer.Time(true, "common", Iterations, () => { if (GenCommon <bool>(true)) { ran += GenCommon <int>(false); } }); CodeTimer.Time(true, "class", Iterations, () => { if (GenClass <bool>(true)) { ran += GenClass <int>(false); } }); //CodeTimer.Time(true, "func", Iterations, () => //{ // if (GenFunc<bool>(true)) // { // ran += GenFunc<int>(false); // } //}); return(ran); }
private static void TestStringBuilder() { int iteration = 100 * 1000; CodeTimer.Time("String Concat", iteration, () => { var s = "1"; for (int i = 1; i < 10; i++) { s = s + "1"; } }, Print); CodeTimer.Time("StringBuilder Concat", iteration, () => { var s = new StringBuilder(); for (int i = 1; i < 10; i++) { s.Append("1"); } }, Print); ShowResult(result.ToString()); }
static void Main(string[] args) { User u = new User(); CodeTimer.Initialize(); CodeTimer.Time("MethodInfo", 1000000, () => GetName2(u)); CodeTimer.Time("dynamic", 1000000, () => GetName3(u)); CodeTimer.Time("Literacy", 1000000, () => GetName(u)); var tester = new TesterBase[] { new LinqTester(), new CreateDelegateTester(), new LiteracyTester(), }; foreach (var t in tester) { t.TestCount = 1000000; t.State = new User() { Name = "blqw1" }; t.Start(); } }
public override void Test() { foreach (var item in Mappers) { CodeTimer.Time(item.Key, 100000, () => item.Value.Map()); } }
public void AutoRestEventTest() { CodeTimer.Time("AutoResetEvent(false)", () =>//无信号,可以通过WaitOne 阻塞线程的执行,通过Set发出信号唤醒等待的线程 { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Run!"); are.Set(); }); are.WaitOne(); } }); CodeTimer.Time("AutoResetEvent(true)", () =>//有信号表示终止状态,即线程属于闲置状态 { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(true)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Not Run!"); are.Set(); }); are.WaitOne();//不会等待子线程的结束 } }); }
static void Main(string[] args) {// 看看yield return的效果 foreach (int i in YieldReturn()) { Console.WriteLine(i); } int iteration = 100000; CodeTimer.Time("StringBuilder Spend:", iteration, () => { StringBuilder sb = new StringBuilder(); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.ToString(); }); CodeTimer.Time("StringBuilderCache Spend:", iteration, () => { StringBuilder sb = StringBuilderCache.Acquire(); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); sb.Append("Hello World"); StringBuilderCache.GetStringAndRelease(sb); }); Console.ReadKey(); }
public void DirectInvokeTest2() { var obj = new InvokeMethod(); CodeTimer.Time("DirectInvokeTest.Create", CreateTimes, () => new InvokeMethod()); CodeTimer.Time("DirectInvokeTest", InvokeTimes, () => obj.Do(InvokeTimes)); }
private static void TestGuidedMissileSystem(Random rand, CodeTimer timer) { GuidedMissileSystem instance = new GuidedMissileSystem(); Console.WriteLine(instance.Solution(new[] { 389, 207, 155, 300, 299, 170, 158, 65 })); Console.ReadKey(true); for (int i = 0; i < 1000; i++) { var len = rand.Next(8) + 3; var arr = new int[len]; for (int j = 0; j < arr.Length; j++) { arr[j] = rand.Next(500); } int solution = -1; var codeTimerResult = timer.Time(10, () => { solution = instance.Solution(arr); }); ShowConsole(new Dictionary <string, object>() { { nameof(arr), JsonConvert.SerializeObject(arr) }, { nameof(solution), solution }, { nameof(codeTimerResult), codeTimerResult } }); } }
public static void Run() { CodeTimer.Initialize(); var type = typeof(MessageTest <CmdTest>); var ctor = type.GetConstructors()[2]; ObjectActivator <object> createdActivator = ActivatorHelper.GetActivator <object>(ctor); var input = new CmdTest(); var header = new MessageHeaderTest(); object tmpObj = null; var count = 1000000; CodeTimer.Time("new instance", count, () => { tmpObj = new MessageTest <CmdTest>(input, header); }); CodeTimer.Time("exp tree", count, () => { tmpObj = createdActivator(input, header); }); CodeTimer.Time("Activator.CreateInstance", count, () => { tmpObj = Activator.CreateInstance(type, input, header); }); CodeTimer.Time("exp tree2", count, () => { tmpObj = ActivatorHelper.CreateInstance(type, input, header); }); }
private static void TestSyncDemo(CodeTimer timer) { SyncDemo demo = new SyncDemo(); List <int> res = null; CodeTimerResult codeTimerResult; for (int i = 0; i < 10; i++) { codeTimerResult = timer.Time(1, (() => { res = demo.Demo(); })); ConsoleTools.ShowConsole(new Dictionary <string, object>() { //System.InvalidOperationException:“Collection was modified; enumeration operation may not execute.” // 由于存在数据返回了 但由于创建了Task.Run 即还存在其他线程正在修改的情况 { "Demo", JsonConvert.SerializeObject(res) }, { nameof(codeTimerResult), codeTimerResult }, { "isRepeat", res.IndexOf(res[0], 1) } }); codeTimerResult = timer.Time(1, (() => { res = demo.Demo2().Result; })); ConsoleTools.ShowConsole(new Dictionary <string, object>() { { "Demo2", JsonConvert.SerializeObject(res) }, { nameof(codeTimerResult), codeTimerResult }, { "isRepeat", res.IndexOf(res[0], 1) } }); codeTimerResult = timer.Time(1, (() => { res = demo.Demo3().Result; })); ConsoleTools.ShowConsole(new Dictionary <string, object>() { { "Demo3", JsonConvert.SerializeObject(res) }, { nameof(codeTimerResult), codeTimerResult }, { "isRepeat", res.IndexOf(res[0], 1) } }); } }
static long MeasureSearchMethods() { const int iterations = 1000000; long ran = 0; var source = new[] { "Connection", "KeepAlive", "TransferEncoding", "WwwAuthenticate", "Server" }; Array.Sort(source, StringComparer.OrdinalIgnoreCase); var sortedSet = new SortedSet <string>(source, StringComparer.OrdinalIgnoreCase); var hashSet = new HashSet <string>(source); CodeTimer.Time( true, "binary search", iterations, () => { if (Array.BinarySearch(source, "Server1", StringComparer.OrdinalIgnoreCase) != 0) { ran += 1; } }); CodeTimer.Time( true, "sorted set search", iterations, () => { if (sortedSet.Contains("Server1", StringComparer.OrdinalIgnoreCase)) { ran += 1; } }); CodeTimer.Time( true, "hash set search", iterations, () => { if (hashSet.Contains("Server1", StringComparer.OrdinalIgnoreCase)) { ran += 1; } }); return(ran); }
static void FailHack2() { CodeTimer.Time(true, "async void hack2", Iterations, () => { Task t = TestMethodFailureAsync(); OnFaultOrSuccessAsyncHack2(t, FaultOrSuccessContinuationAction); }); }
public static void Start(IRunner runner, RunType runType) { runner.Init(runType); CodeTimer.Time( runner.Name , Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Iteration"] ?? "10000") , () => runner.Start()); }
static void FailHack() { CodeTimer.Time(true, "async void hack", Iterations, () => { Task t = TestMethodFailureAsync(); OnFaultOrSuccessAsyncHack(t, SuccessAction, "PUBLISH"); }); }
public void DelegateInvokeTest2() { var obj = new InvokeMethod(); Action <int> a = null; CodeTimer.Time("DelegateInvokeTest.Create", CreateTimes, () => a = CreateDelegate(obj)); CodeTimer.Time("DelegateInvokeTest", InvokeTimes, () => a.Invoke(InvokeTimes)); }
private static void ShowSplash() { CodeTimer.Time("ShowSplash", () => { using (var form = new SplashForm()) form.ShowDialog(); }); }
public void ReflectionInvokeTest2() { var obj = new InvokeMethod(); MethodInfo m = null; CodeTimer.Time("ReflectionInvoke.Create", CreateTimes, () => m = CreateMethodInfo(obj)); CodeTimer.Time("ReflectionInvoke", InvokeTimes, () => ReflectionInvoke(m, obj)); }
public void GenerateDelegateInvokeTest2() { JobAction a = null; CodeTimer.Time("Generate Delegate Create", CreateTimes, () => a = CreateDelegateAction()); CodeTimer.Time("Generated Delegate InvokeTest", InvokeTimes, () => a(InvokeTimes)); }
public void TimeTest() { string name = "Hello"; // TODO: Initialize to an appropriate value int iteration = 1; // TODO: Initialize to an appropriate value Action action = DoSomeThing; // TODO: Initialize to an appropriate value CodeTimer.Time(name, iteration, action); // Assert.Inconclusive("A method that does not return a value cannot be verified."); }
public static long Run() { long ran = 0; const int iterations = 1000000; const string TransactionRowKeyPrefix = "__tx"; ParameterExpression queryExpressionParameter = Expression.Parameter(typeof(DynamicTableEntity)); MemberExpression partitionKeyPropertyExpression = Expression.Property( queryExpressionParameter, typeof(DynamicTableEntity).GetProperty(GetPropertyName <DynamicTableEntity>(x => x.PartitionKey))); MemberExpression rowKeyPropertyAccess = Expression.Property( queryExpressionParameter, typeof(DynamicTableEntity).GetProperty(GetPropertyName <DynamicTableEntity>(x => x.RowKey))); MethodInfo stringCompareToMethodInfo = typeof(string).GetMethod("CompareTo", new[] { typeof(string) }); BinaryExpression filterTransactionRowsExpression = Expression.And( Expression.GreaterThan( Expression.Call(rowKeyPropertyAccess, stringCompareToMethodInfo, Expression.Constant(TransactionRowKeyPrefix)), Expression.Constant(0)), Expression.LessThan( Expression.Call(rowKeyPropertyAccess, stringCompareToMethodInfo, Expression.Constant(TransactionRowKeyPrefix + ":")), Expression.Constant(0))); Func <string, IEnumerable <string>, Expression <Func <DynamicTableEntity, bool> > > composeTargetedReadFilterEx = (partitionKey, rowKeys) => { Expression eqFilter = null; foreach (string rowKey in rowKeys) { BinaryExpression currentExpression = Expression.Equal(rowKeyPropertyAccess, Expression.Constant(rowKey)); eqFilter = eqFilter == null ? currentExpression : Expression.Or(eqFilter, currentExpression); } BinaryExpression result = Expression.And( Expression.Equal( partitionKeyPropertyExpression, Expression.Constant(partitionKey)), Expression.Or( eqFilter, filterTransactionRowsExpression)); return(Expression.Lambda <Func <DynamicTableEntity, bool> >(result, queryExpressionParameter)); }; CodeTimer.Time(true, "prebuilt", iterations, () => { Expression <Func <DynamicTableEntity, bool> > exp = composeTargetedReadFilterEx("a", new[] { "1", "2" }); if (exp.Body != null) { ran++; } }); CodeTimer.Time(true, "rebuilt", iterations, () => { ran = EvaluateRebuilt(TransactionRowKeyPrefix, ran); }); return(ran); }
/// <summary> /// 计时 /// </summary> /// <param name="times">次数</param> /// <param name="action">需要计时的委托</param> /// <param name="needTimeOne">是否需要预热</param> /// <returns></returns> public static CodeTimer Time(Int32 times, Action<Int32> action, Boolean needTimeOne = true) { CodeTimer timer = new CodeTimer(); timer.Times = times; timer.Action = action; if (needTimeOne) timer.TimeOne(); timer.Time(); return timer; }
public void TestForCodeTimer() { var CachedProcessPriorityClass = Process.GetCurrentProcess().PriorityClass; var CachedThreadPriority = Thread.CurrentThread.Priority; using (var timer = new CodeTimer()) { timer.Initialize(); var result = timer.Time(1, () => { }); } Assert.AreEqual(CachedProcessPriorityClass, Process.GetCurrentProcess().PriorityClass); Assert.AreEqual(CachedThreadPriority, Thread.CurrentThread.Priority); }
/// <summary> /// 计时,并用控制台输出行 /// </summary> /// <param name="title">标题</param> /// <param name="times">次数</param> /// <param name="action">需要计时的委托</param> /// <param name="needTimeOne">是否需要预热</param> public static void TimeLine(String title, Int32 times, Action<Int32> action, Boolean needTimeOne = true) { Console.Write("{0}{1}:", new String(' ', 16 - Encoding.Default.GetByteCount(title)), title); CodeTimer timer = new CodeTimer(); timer.Times = times; timer.Action = action; timer.ShowProgress = true; ConsoleColor currentForeColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; if (needTimeOne) timer.TimeOne(); timer.Time(); Console.WriteLine(timer.ToString()); Console.ForegroundColor = currentForeColor; }