Here are the examples of the csharp api System.Diagnostics.Stopwatch.Start() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
3566 Examples
19
Source : Helper.cs
with MIT License
from 0ffffffffh
with MIT License
from 0ffffffffh
public void Begin()
{
sw.Start();
}
19
Source : Program.cs
with MIT License
from 0x1000000
with MIT License
from 0x1000000
private static async Task ExecScenarioAll(IScenario scenario, string msSqlConnectionString, string pgSqlConnectionString, string mySqlConnectionString)
{
Stopwatch stopwatch = new Stopwatch();
Console.WriteLine();
Console.WriteLine("-MS SQL Test-------");
stopwatch.Restart();
await ExecMsSql(scenario, msSqlConnectionString);
stopwatch.Stop();
Console.WriteLine($"-MS SQL Test End: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine("-Postgres Test-----");
stopwatch.Start();
await ExecNpgSql(scenario, pgSqlConnectionString);
stopwatch.Stop();
Console.WriteLine($"-Postgres Test End: {stopwatch.ElapsedMilliseconds} ms");
Console.WriteLine();
Console.WriteLine("-MY SQL Test-------");
stopwatch.Restart();
await ExecMySql(scenario, mySqlConnectionString);
stopwatch.Stop();
Console.WriteLine($"-MY SQL Test End: {stopwatch.ElapsedMilliseconds} ms");
}
19
Source : MelonMain.cs
with GNU General Public License v3.0
from 1330-Studios
with GNU General Public License v3.0
from 1330-Studios
internal void Set(bool val = false) {
#if AGGRESSIVE_TACTICS
//IL2CPP.ResolveICall<intIntPtrDelegate>("UnityEngine.QualitySettings::set_vSyncCount")(0);
var mods = AppDomain.CurrentDomain.Getreplacedemblies();
GC = GCTime();
MelonCoroutines.Start(GC);
#else
var mods = MelonHandler.Mods.Select(a=>a.replacedembly).ToArray();
#endif
if (!val) return;
var sw = new Stopwatch();
sw.Start();
var methodCount = 0;
#region RuntimeHelpers
for (var i = 0; i < mods.Count(); i++) {
var asm = mods[i];
var types = asm.GetTypes();
for (var j = 0; j < types.Length; j++)
try {
var type = types[j];
var methods = AccessTools.GetDeclaredMethods(type);
for (var k = 0; k < methods.Count; k++) {
RuntimeHelpers.PrepareMethod(methods[k].MethodHandle);
methodCount += 1;
}
} catch {}
}
#endregion
sw.Stop();
MelonLogger.Msg($"Optimized {methodCount:N0} methods in {sw.Elapsed.Milliseconds:N0} milliseconds!");
}
19
Source : Client.cs
with MIT License
from 1ZouLTReX1
with MIT License
from 1ZouLTReX1
public static void StartStopWatch()
{
stopWatch.Start();
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
cli.Set("TestMGet_null1", "");
RedisHelper.Set("TestMGet_null1", "");
sedb.StringSet("TestMGet_string1", String);
ThreadPool.SetMinThreads(10001, 10001);
Stopwatch sw = new Stopwatch();
var tasks = new List<Task>();
var results = new ConcurrentQueue<string>();
cli.FlushDb();
while (results.TryDequeue(out var del)) ;
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await cli.SetAsync(tmp, String);
var val = await cli.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
//FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
//FreeRedis.Internal.AsyncRedisSocket.sw.Start();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await cli.SetAsync(tmp, String);
var val = await cli.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
//var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
//sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
using (var pipe = cli.StartPipe())
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
pipe.Set(tmp, String);
var val = pipe.Get(tmp);
}
var vals = pipe.EndPipe();
for (var a = 1; a < 200000; a += 2)
{
var val = vals[a].ToString();
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}
sw.Stop();
Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
// cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
//sw.Stop();
//Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
//{
// using (var rds = cli.GetTestRedisSocket())
// {
// var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
// rds.Write(cmd);
// cmd.Read<string>();
// }
//}
//sw.Stop();
//Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
//if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
while (results.TryDequeue(out var del)) ;
cli.FlushDb();
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
sedb.StringSet("key1", (string)null);
var val111 = sedb.StringGet("key1");
RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,asyncPipeline=true,preheat=100,poolsize=100"));
cli.Set("TestMGet_null1", "");
RedisHelper.Set("TestMGet_null1", "");
sedb.StringSet("TestMGet_string1", String);
ThreadPool.SetMinThreads(10001, 10001);
Stopwatch sw = new Stopwatch();
var tasks = new List<Task>();
var results = new ConcurrentQueue<string>();
cli.FlushDb();
results.Clear();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("StackExchange(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, String);
var val = sedb.StringGet(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchange(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("StackExchangeAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await sedb.StringSetAsync(tmp, String);
var val = await sedb.StringGetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("StackExchangeAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("FreeRedis(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, String);
var val = cli.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("FreeRedis(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
//sw.Reset();
//sw.Start();
//Task.Run(async () =>
//{
// for (var a = 0; a < 100000; a++)
// {
// var tmp = Guid.NewGuid().ToString();
// await cli.SetAsync(tmp, String);
// var val = await cli.GetAsync(tmp);
// if (val != String) throw new Exception("not equal");
// results.Enqueue(val);
// }
//}).Wait();
//sw.Stop();
//Console.WriteLine("FreeRedisAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
//tasks.Clear();
//results.Clear();
//cli.FlushDb();
//FreeRedis.Internal.AsyncRedisSocket.sb.Clear();
//FreeRedis.Internal.AsyncRedisSocket.sw.Start();
//sw.Reset();
//sw.Start();
//tasks = new List<Task>();
//for (var a = 0; a < 100000; a++)
//{
// tasks.Add(Task.Run(async () =>
// {
// var tmp = Guid.NewGuid().ToString();
// await cli.SetAsync(tmp, String);
// var val = await cli.GetAsync(tmp);
// if (val != String) throw new Exception("not equal");
// results.Enqueue(val);
// }));
//}
//Task.WaitAll(tasks.ToArray());
//sw.Stop();
////var sbstr = FreeRedis.Internal.AsyncRedisSocket.sb.ToString()
////sbstr = sbstr + sbstr.Split("\r\n").Length + "条消息 ;
//Console.WriteLine("FreeRedisAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
//tasks.Clear();
//results.Clear();
//cli.FlushDb();
sw.Reset();
sw.Start();
using (var pipe = cli.StartPipe())
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
pipe.Set(tmp, String);
var val = pipe.Get(tmp);
}
var vals = pipe.EndPipe();
for (var a = 1; a < 200000; a += 2)
{
var val = vals[a].ToString();
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}
sw.Stop();
Console.WriteLine("FreeRedisPipeline(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
results.Clear();
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
// cli.Call(new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String));
//sw.Stop();
//Console.WriteLine("FreeRedis2: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
results.Clear();
cli.FlushDb();
//sw.Reset();
//sw.Start();
//for (var a = 0; a < 100000; a++)
//{
// using (var rds = cli.GetTestRedisSocket())
// {
// var cmd = new CommandPacket("SET").Input("TestMGet_string1").InputRaw(String);
// rds.Write(cmd);
// cmd.Read<string>();
// }
//}
//sw.Stop();
//Console.WriteLine("FreeRedis4: " + sw.ElapsedMilliseconds + "ms");
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
sw.Stop();
Console.WriteLine("CSRedisCore(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(() =>
{
var tmp = Guid.NewGuid().ToString();
RedisHelper.Set(tmp, String);
var val = RedisHelper.Get(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCore(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
Task.Run(async () =>
{
for (var a = 0; a < 100000; a++)
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}
}).Wait();
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(0-100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count);
tasks.Clear();
results.Clear();
cli.FlushDb();
sw.Reset();
sw.Start();
tasks = new List<Task>();
for (var a = 0; a < 100000; a++)
{
tasks.Add(Task.Run(async () =>
{
var tmp = Guid.NewGuid().ToString();
await RedisHelper.SetAsync(tmp, String);
var val = await RedisHelper.GetAsync(tmp);
//if (val != String) throw new Exception("not equal");
results.Enqueue(val);
}));
}
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine("CSRedisCoreAsync(Task.WaitAll 100000): " + sw.ElapsedMilliseconds + "ms results: " + results.Count + "\r\n");
tasks.Clear();
results.Clear();
cli.FlushDb();
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
var info = cli.Info();
var info1 = cli.Info("server");
RedisHelper.Initialization(new CSRedis.CSRedisClient("127.0.0.1:6379,database=2"));
cli.Set("TestMGet_null1", String);
RedisHelper.Set("TestMGet_null1", String);
sedb.StringSet("TestMGet_string1", String);
Stopwatch sw = new Stopwatch();
sw.Start();
cli.Set("TestMGet_string1", String);
cli.Set("TestMGet_bytes1", Bytes);
cli.Set("TestMGet_string2", String);
cli.Set("TestMGet_bytes2", Bytes);
cli.Set("TestMGet_string3", String);
cli.Set("TestMGet_bytes3", Bytes);
sw.Stop();
Console.WriteLine("FreeRedis: " + sw.ElapsedMilliseconds + "ms");
sw.Reset();
sw.Start();
cli.Set("TestMGet_string1", String);
cli.Set("TestMGet_bytes1", Bytes);
cli.Set("TestMGet_string2", String);
cli.Set("TestMGet_bytes2", Bytes);
cli.Set("TestMGet_string3", String);
cli.Set("TestMGet_bytes3", Bytes);
sw.Stop();
Console.WriteLine("FreeRedis: " + sw.ElapsedMilliseconds + "ms");
sw.Reset();
sw.Start();
RedisHelper.Set("TestMGet_string1", String);
RedisHelper.Set("TestMGet_bytes1", Bytes);
RedisHelper.Set("TestMGet_string2", String);
RedisHelper.Set("TestMGet_bytes2", Bytes);
RedisHelper.Set("TestMGet_string3", String);
RedisHelper.Set("TestMGet_bytes3", Bytes);
sw.Stop();
Console.WriteLine("CSRedisCore: " + sw.ElapsedMilliseconds + "ms");
sw.Reset();
sw.Start();
sedb.StringSet("TestMGet_string1", String);
sedb.StringSet("TestMGet_bytes1", Bytes);
sedb.StringSet("TestMGet_string2", String);
sedb.StringSet("TestMGet_bytes2", Bytes);
sedb.StringSet("TestMGet_string3", String);
sedb.StringSet("TestMGet_bytes3", Bytes);
sw.Stop();
Console.WriteLine("StackExchange: " + sw.ElapsedMilliseconds + "ms");
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
//预热
cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
sedb.StringSet(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, "我也不知道为什么刚刚好十五个字");
var val = cli.Get(tmp);
if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
}
stopwatch.Stop();
Console.WriteLine("FreeRedis:"+stopwatch.ElapsedMilliseconds);
//stopwatch.Restart();
// csredis 会出现连接不能打开的情况
//for (int i = 0; i < 100; i++)
//{
// var tmp = Guid.NewGuid().ToString();
// csredis.Set(tmp, "我也不知道为什么刚刚好十五个字");
// _ = csredis.Get(tmp);
//}
//stopwatch.Stop();
//Console.WriteLine("csredis:" + stopwatch.ElapsedMilliseconds);
stopwatch.Restart();
for (int i = 0; i < 10000; i++)
{
var tmp = Guid.NewGuid().ToString();
sedb.StringSet(tmp, "我也不知道为什么刚刚好十五个字");
var val = sedb.StringGet(tmp);
if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
}
stopwatch.Stop();
Console.WriteLine("Seredis:" + stopwatch.ElapsedMilliseconds);
cli.Subscribe("abc", (chan, msg) =>
{
Console.WriteLine($"FreeRedis {chan} => {msg}");
});
seredis.GetSubscriber().Subscribe("abc", (chan, msg) =>
{
Console.WriteLine($"Seredis {chan} => {msg}");
});
Console.ReadKey();
return;
}
19
Source : Program.cs
with MIT License
from 2881099
with MIT License
from 2881099
static void Main(string[] args)
{
//预热
cli.Set(Guid.NewGuid().ToString(), "我也不知道为什么刚刚好十五个字");
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 10000; i++)
{
var tmp = Guid.NewGuid().ToString();
cli.Set(tmp, "我也不知道为什么刚刚好十五个字");
var val = cli.Get(tmp);
if (val != "我也不知道为什么刚刚好十五个字") throw new Exception("not equal");
}
stopwatch.Stop();
Console.WriteLine("FreeRedis:" + stopwatch.ElapsedMilliseconds);
}
19
Source : RedisClient.cs
with MIT License
from 2881099
with MIT License
from 2881099
internal protected virtual T LogCall<T>(CommandPacket cmd, Func<T> func)
{
cmd.Prefix(Prefix);
var isnotice = this.Notice != null;
if (isnotice == false && this.Interceptors.Any() == false) return func();
Exception exception = null;
T ret = default(T);
var isaopval = false;
IInterceptor[] aops = new IInterceptor[this.Interceptors.Count + (isnotice ? 1 : 0)];
Stopwatch[] aopsws = new Stopwatch[aops.Length];
for (var idx = 0; idx < aops.Length; idx++)
{
aopsws[idx] = new Stopwatch();
aopsws[idx].Start();
aops[idx] = isnotice && idx == aops.Length - 1 ? new NoticeCallInterceptor(this) : this.Interceptors[idx]?.Invoke();
var args = new InterceptorBeforeEventArgs(this, cmd, typeof(T));
aops[idx].Before(args);
if (args.ValueIsChanged && args.Value is T argsValue)
{
isaopval = true;
ret = argsValue;
}
}
try
{
if (isaopval == false) ret = func();
return ret;
}
catch (Exception ex)
{
exception = ex;
throw;
}
finally
{
for (var idx = 0; idx < aops.Length; idx++)
{
aopsws[idx].Stop();
var args = new InterceptorAfterEventArgs(this, cmd, typeof(T), ret, exception, aopsws[idx].ElapsedMilliseconds);
aops[idx].After(args);
}
}
}
19
Source : SpeedtestHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private int GetTcpingTime(string url, int port)
{
int responseTime = -1;
try
{
if (!IPAddress.TryParse(url, out IPAddress ipAddress))
{
IPHostEntry ipHostInfo = System.Net.Dns.GetHostEntry(url);
ipAddress = ipHostInfo.AddressList[0];
}
Stopwatch timer = new Stopwatch();
timer.Start();
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
Socket clientSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = clientSocket.BeginConnect(endPoint, null, null);
if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
throw new TimeoutException("connect timeout (5s): " + url);
clientSocket.EndConnect(result);
timer.Stop();
responseTime = timer.Elapsed.Milliseconds;
clientSocket.Close();
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
}
return responseTime;
}
19
Source : SpeedtestHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private string GetRealPingTime(string url, WebProxy webProxy, out int responseTime)
{
string msg = string.Empty;
responseTime = -1;
try
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.Timeout = 5000;
myHttpWebRequest.Proxy = webProxy;//new WebProxy(Global.Loopback, Global.httpPort);
Stopwatch timer = new Stopwatch();
timer.Start();
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode != HttpStatusCode.OK
&& myHttpWebResponse.StatusCode != HttpStatusCode.NoContent)
{
msg = myHttpWebResponse.StatusDescription;
}
timer.Stop();
responseTime = timer.Elapsed.Milliseconds;
myHttpWebResponse.Close();
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
msg = ex.Message;
}
return msg;
}
19
Source : JobAnimationCurveTests.cs
with MIT License
from 5argon
with MIT License
from 5argon
private (long mainTicks, long jobTicks) MainThreadPerformanceTest(AnimationCurve ac, int iterationCount)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
var jac = new JobAnimationCurve(ac, Allocator.Temp);
float[] evaluated = new float[iterationCount];
sw.Start();
for (int i = 0; i < evaluated.Length; i++)
{
evaluated[i] = jac.Evaluate(i / (float)iterationCount);
}
sw.Stop();
var jobTicks = sw.ElapsedTicks;
sw.Reset();
sw.Start();
for (int i = 0; i < evaluated.Length; i++)
{
evaluated[i] = ac.Evaluate(i / (float)iterationCount);
}
sw.Stop();
var mainTicks = sw.ElapsedTicks;
jac.Dispose();
return (mainTicks, jobTicks);
}
19
Source : JobAnimationCurveTests.cs
with MIT License
from 5argon
with MIT License
from 5argon
private (long mainTicks, long jobTicks) TestEvaluate(AnimationCurve ac, int iterationCount)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
var jac = new JobAnimationCurve(ac, Allocator.TempJob);
NativeArray<float> evaluated = new NativeArray<float>(iterationCount, Allocator.TempJob);
NativeArray<float> jobEvaluated = new NativeArray<float>(iterationCount, Allocator.TempJob);
var job = new CurveEvaluationJob
{
evaluated = jobEvaluated,
jobAnimationCurve = jac
}.Schedule(iterationCount, testEvaluateBatchCount, default(JobHandle));
sw.Start();
for (int i = 0; i < evaluated.Length; i++)
{
evaluated[i] = ac.Evaluate(i / (float)iterationCount);
}
sw.Stop();
var mainTicks = sw.ElapsedTicks;
sw.Reset();
sw.Start();
job.Complete();
sw.Stop();
var jobTicks = sw.ElapsedTicks;
for (int i = 0; i < evaluated.Length; i++)
{
//Within 0.00001f, it is a bit inaccurate.
replacedert.That(evaluated[i], Is.EqualTo(jobEvaluated[i]).Within(0.0001f),
$"At index {i} (time {i / (float)iterationCount}) there is a difference of Unity {evaluated[i]} and Job {jobEvaluated[i]} ({evaluated[i] - jobEvaluated[i]})");
}
evaluated.Dispose();
jobEvaluated.Dispose();
jac.Dispose();
return (mainTicks, jobTicks);
}
19
Source : JobBase.cs
with Apache License 2.0
from 91270
with Apache License 2.0
from 91270
public async Task<string> ExecuteJob(IJobExecutionContext context, Func<Task> job)
{
string jobHistory = $"Run Job [Id:{context.JobDetail.Key.Name},Group:{context.JobDetail.Key.Group}]";
try
{
var s = context.Trigger.Key.Name;
//记录Job时间
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
//执行任务
await job();
stopwatch.Stop();
jobHistory += $", Succeed , Elapsed:{stopwatch.Elapsed.TotalMilliseconds} ms";
}
catch (Exception ex)
{
JobExecutionException e2 = new JobExecutionException(ex);
//true 是立即重新执行任务
e2.RefireImmediately = true;
jobHistory += $", Fail ,Exception:{ex.Message}";
}
return jobHistory;
}
19
Source : UMAAssetIndexer.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public T Getreplacedet<T>(int nameHash, string[] foldersToSearch = null) where T : UnityEngine.Object
{
System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
st.Start();
System.Type ot = typeof(T);
Dictionary<string, replacedereplacedem> TypeDic = (Dictionary<string, replacedereplacedem>)TypeLookup[ot];
string replacedetName = "";
int replacedetHash = -1;
foreach (KeyValuePair<string, replacedereplacedem> kp in TypeDic)
{
replacedetName = "";
replacedetHash = -1;
GetEvilreplacedetNameAndHash(typeof(T), kp.Value.Item, ref replacedetName, replacedetHash);
if (replacedetHash == nameHash)
{
if (replacedetFolderCheck(kp.Value, foldersToSearch))
{
st.Stop();
if (st.ElapsedMilliseconds > 2)
{
Debug.Log("Getreplacedet 0 for type "+typeof(T).Name+" completed in " + st.ElapsedMilliseconds + "ms");
}
return (kp.Value.Item as T);
}
else
{
st.Stop();
if (st.ElapsedMilliseconds > 2)
{
Debug.Log("Getreplacedet 1 for type " + typeof(T).Name + " completed in " + st.ElapsedMilliseconds + "ms");
}
return null;
}
}
}
st.Stop();
if (st.ElapsedMilliseconds > 2)
{
Debug.Log("Getreplacedet 2 for type " + typeof(T).Name + " completed in " + st.ElapsedMilliseconds + "ms");
}
return null;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long UpdateTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Update Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
Repository<Employee> repository = new Repository<Employee>(con);
repository.Update(emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : UMAGeneratorBuiltin.cs
with Apache License 2.0
from A7ocin
with Apache License 2.0
from A7ocin
public override void Work()
{
if (!IsIdle())
{
stopWatch.Reset();
stopWatch.Start();
OnDirtyUpdate();
ElapsedTicks += stopWatch.ElapsedTicks;
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
stopWatch.Stop();
UMATime.ReportTimeSpendtThisFrameTicks(stopWatch.ElapsedTicks);
}
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long SelectListTest(int count)
{
Stopwatch w = new Stopwatch();
List<Employee> employeeList = new List<Employee>();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
Repository<Employee> repository = new Repository<Employee>(con);
employeeList = repository.ReadAll().ToList();
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long InsertTest(int count)
{
PerformanceTest.TruncateTable();
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
con.Execute(@"INSERT Employee(EmployeeId, EmployeeName, Location, Department, Designation, DOB, CTC)
VALUES(@EmployeeId, @EmployeeName, @Location, @Department, @Designation, @DOB, @CTC)", emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long InsertTest(int count)
{
PerformanceTest.TruncateTable();
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling(( Convert.ToDecimal(i) / Convert.ToDecimal(count))*12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"INSERT INTO Employee (EmployeeId, EmployeeName, Location, Department, Designation, DOB, CTC)
VALUES(@EmployeeId, @EmployeeName, @Location, @Department, @Designation, @DOB, @CTC)";
cmd.Parameters.AddWithValue("EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("Location", emp.Location);
cmd.Parameters.AddWithValue("Department", emp.Department);
cmd.Parameters.AddWithValue("Designation", emp.Designation);
cmd.Parameters.AddWithValue("DOB", emp.DOB);
cmd.Parameters.AddWithValue("CTC", emp.CTC);
cmd.ExecuteNonQuery();
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long SelectListTest(int count)
{
Stopwatch w = new Stopwatch();
List<Employee> employeeList = new List<Employee>();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = $@"SELECT TOP {count} EmployeeId, EmployeeName, Location, Department, Designation, DOB, CTC FROM Employee";
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
employeeList.Add(new Employee()
{
EmployeeId = rdr.GetInt32(0),
EmployeeName = rdr.GetString(1),
Location = rdr.GetString(2),
Department = rdr.GetString(3),
Designation = rdr.GetString(4),
DOB = rdr.GetDateTime(5),
CTC = rdr.GetDecimal(6)
});
}
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long SelectTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"SELECT EmployeeId, EmployeeName, Location, Department, Designation, DOB, CTC FROM Employee WHERE EmployeeId=@EmployeeId";
cmd.Parameters.AddWithValue("EmployeeId", i);
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
Employee emp = new Employee()
{
EmployeeId = rdr.GetInt32(0),
EmployeeName = rdr.GetString(1),
Location = rdr.GetString(2),
Department = rdr.GetString(3),
Designation = rdr.GetString(4),
DOB = rdr.GetDateTime(5),
CTC = rdr.GetDecimal(6)
};
}
}
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long UpdateTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Update Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"UPDATE Employee SET EmployeeName=@EmployeeName,
Location=@Location, Department=@Department,
Designation=@Designation, DOB=@DOB, CTC=@CTC
WHERE EmployeeId=@EmployeeId";
cmd.Parameters.AddWithValue("EmployeeId", emp.EmployeeId);
cmd.Parameters.AddWithValue("EmployeeName", emp.EmployeeName);
cmd.Parameters.AddWithValue("Location", emp.Location);
cmd.Parameters.AddWithValue("Department", emp.Department);
cmd.Parameters.AddWithValue("Designation", emp.Designation);
cmd.Parameters.AddWithValue("DOB", emp.DOB);
cmd.Parameters.AddWithValue("CTC", emp.CTC);
cmd.ExecuteNonQuery();
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long InsertTest(int count)
{
PerformanceTest.TruncateTable();
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
Repository<Employee> repository = new Repository<Employee>(con);
repository.Add(emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long SelectTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Repository<Employee> repository = new Repository<Employee>(con);
repository.ReadOne(i);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long SelectListTest(int count)
{
Stopwatch w = new Stopwatch();
List<Employee> employeeList = new List<Employee>();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
employeeList = con.Query<Employee>("SELECT * FROM Employee").ToList();
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long SelectTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
con.QueryFirst<Employee>("SELECT * FROM Employee WHERE EmployeeId=@EmployeeId", new { EmployeeId=i });
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTest.cs
with Apache License 2.0
from aadreja
with Apache License 2.0
from aadreja
public long UpdateTest(int count)
{
Stopwatch w = new Stopwatch();
using (SqlConnection con = new SqlConnection(PerformanceTest.ConString))
{
con.Open();
w.Start();
for (int i = 1; i <= count; i++)
{
Employee emp = new Employee()
{
EmployeeId = i,
EmployeeName = "Update Employee " + i,
Location = "Location " + i,
Department = "Department " + i,
Designation = "Designation " + i,
DOB = new DateTime(1978, (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 12m), (int)Math.Ceiling((Convert.ToDecimal(i) / Convert.ToDecimal(count)) * 25m)),
CTC = i * 1000m
};
con.Execute(@"UPDATE Employee SET EmployeeName = @EmployeeName,
Location = @Location, Department = @Department,
Designation = @Designation, DOB = @DOB, CTC = @CTC
WHERE EmployeeId = @EmployeeId", emp);
}
w.Stop();
con.Close();
}
return w.ElapsedMilliseconds;
}
19
Source : PerformanceTests.cs
with MIT License
from ababik
with MIT License
from ababik
[TestMethod]
public void SetFirstLevelProperyTest()
{
// ~12 ms
var remute = new Remute();
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 1000; i++)
{
var organization = new Organization("organization 1", new Department("department 1", new Employee(Guid.NewGuid(), "developer", "manager"), null));
var actual = remute.With(organization, x => x.Name, "organization 2");
}
stopwatch.Stop();
var time = stopwatch.ElapsedMilliseconds;
Console.WriteLine(time);
}
19
Source : PerformanceTests.cs
with MIT License
from ababik
with MIT License
from ababik
[TestMethod]
public void SetNestedProperyTest()
{
// ~19 ms
var remute = new Remute();
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 1000; i++)
{
var organization = new Organization("organization 1", new Department("department 1", new Employee(Guid.NewGuid(), "developer", "manager"), null));
var actual = remute.With(organization, x => x.DevelopmentDepartment.Manager.FirstName, "name");
}
stopwatch.Stop();
var time = stopwatch.ElapsedMilliseconds;
Console.WriteLine(time);
}
19
Source : PerformanceBehaviour.cs
with MIT License
from Abdulrhman5
with MIT License
from Abdulrhman5
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
{
_timer.Start();
var response = await next();
_timer.Stop();
var elapsedMilliseconds = _timer.ElapsedMilliseconds;
if (elapsedMilliseconds > 500)
{
var requestName = typeof(TRequest).Name;
var userId = _userDataManager.GetCurrentUser()?.UserId ?? string.Empty;
_logger.LogWarning("Transaction.Service Long Running Request: {Name} ({ElapsedMilliseconds} milliseconds) {@UserId} {@Request}",
requestName, elapsedMilliseconds, userId, request);
}
return response;
}
19
Source : MixedRealityToolkitVisualProfiler.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private void Reset()
{
if (defaultMaterial == null)
{
defaultMaterial = new Material(Shader.Find("Hidden/Internal-Colored"));
defaultMaterial.SetFloat("_ZWrite", 1.0f);
defaultMaterial.SetFloat("_ZTest", (float)UnityEngine.Rendering.CompareFunction.Disabled);
defaultMaterial.renderQueue = 5000;
}
if (defaultInstancedMaterial == null)
{
Shader defaultInstancedShader = Shader.Find("Hidden/Instanced-Colored");
if (defaultInstancedShader != null)
{
defaultInstancedMaterial = new Material(defaultInstancedShader);
defaultInstancedMaterial.enableInstancing = true;
defaultInstancedMaterial.SetFloat("_ZWrite", 1.0f);
defaultInstancedMaterial.SetFloat("_ZTest", (float)UnityEngine.Rendering.CompareFunction.Disabled);
defaultInstancedMaterial.renderQueue = 5000;
}
else
{
Debug.LogWarning("A shader supporting instancing could not be found for the VisualProfiler, falling back to traditional rendering. This may impact performance.");
}
}
if (Application.isPlaying)
{
backgroundMaterial = new Material(defaultMaterial);
foregroundMaterial = new Material(defaultMaterial);
defaultMaterial.renderQueue = foregroundMaterial.renderQueue - 1;
backgroundMaterial.renderQueue = defaultMaterial.renderQueue - 1;
MeshRenderer meshRenderer = new GameObject().AddComponent<TextMesh>().GetComponent<MeshRenderer>();
textMaterial = new Material(meshRenderer.sharedMaterial);
textMaterial.renderQueue = defaultMaterial.renderQueue;
Destroy(meshRenderer.gameObject);
MeshFilter quadMeshFilter = GameObject.CreatePrimitive(PrimitiveType.Quad).GetComponent<MeshFilter>();
if (defaultInstancedMaterial != null)
{
// Create a quad mesh with artificially large bounds to disable culling for instanced rendering.
// TODO: Use shared mesh with normal bounds once Unity allows for more control over instance culling.
quadMesh = quadMeshFilter.mesh;
quadMesh.bounds = new Bounds(Vector3.zero, Vector3.one * float.MaxValue);
}
else
{
quadMesh = quadMeshFilter.sharedMesh;
}
Destroy(quadMeshFilter.gameObject);
}
stopwatch.Reset();
stopwatch.Start();
}
19
Source : MixedRealityToolkitVisualProfiler.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private void LateUpdate()
{
if (window == null)
{
return;
}
using (LateUpdatePerfMarker.Auto())
{
// Update window transformation.
Transform cameraTransform = CameraCache.Main ? CameraCache.Main.transform : null;
if (ShouldShowProfiler && cameraTransform != null)
{
float t = Time.deltaTime * windowFollowSpeed;
window.position = Vector3.Lerp(window.position, CalculateWindowPosition(cameraTransform), t);
window.rotation = Quaternion.Slerp(window.rotation, CalculateWindowRotation(cameraTransform), t);
window.localScale = defaultWindowScale * windowScale;
CalculateBackgroundSize();
}
// Capture frame timings every frame and read from it depending on the frameSampleRate.
FrameTimingManager.CaptureFrameTimings();
++frameCount;
float elapsedSeconds = stopwatch.ElapsedMilliseconds * 0.001f;
if (elapsedSeconds >= frameSampleRate)
{
int cpuFrameRate = (int)(1.0f / (elapsedSeconds / frameCount));
int gpuFrameRate = 0;
// Many platforms do not yet support the FrameTimingManager. When timing data is returned from the FrameTimingManager we will use
// its timing data, else we will depend on the stopwatch.
uint frameTimingsCount = FrameTimingManager.GetLatestTimings((uint)Mathf.Min(frameCount, maxFrameTimings), frameTimings);
if (frameTimingsCount != 0)
{
float cpuFrameTime, gpuFrameTime;
AverageFrameTiming(frameTimings, frameTimingsCount, out cpuFrameTime, out gpuFrameTime);
cpuFrameRate = (int)(1.0f / (cpuFrameTime / frameCount));
gpuFrameRate = (int)(1.0f / (gpuFrameTime / frameCount));
}
// Update frame rate text.
cpuFrameRateText.text = cpuFrameRateStrings[Mathf.Clamp(cpuFrameRate, 0, maxTargetFrameRate)];
if (gpuFrameRate != 0)
{
gpuFrameRateText.gameObject.SetActive(true);
gpuFrameRateText.text = gpuFrameRateStrings[Mathf.Clamp(gpuFrameRate, 0, maxTargetFrameRate)];
}
// Update frame colors.
if (frameInfoVisible)
{
for (int i = frameRange - 1; i > 0; --i)
{
frameInfoColors[i] = frameInfoColors[i - 1];
}
frameInfoColors[0] = CalculateFrameColor(cpuFrameRate);
frameInfoPropertyBlock.SetVectorArray(colorID, frameInfoColors);
}
// Reset timers.
frameCount = 0;
stopwatch.Reset();
stopwatch.Start();
}
// Draw frame info.
if (ShouldShowProfiler && frameInfoVisible)
{
Matrix4x4 parentLocalToWorldMatrix = window.localToWorldMatrix;
if (defaultInstancedMaterial != null)
{
frameInfoPropertyBlock.SetMatrix(parentMatrixID, parentLocalToWorldMatrix);
Graphics.DrawMeshInstanced(quadMesh, 0, defaultInstancedMaterial, frameInfoMatrices, frameInfoMatrices.Length, frameInfoPropertyBlock, UnityEngine.Rendering.ShadowCastingMode.Off, false);
}
else
{
// If a instanced material is not available, fall back to non-instanced rendering.
for (int i = 0; i < frameInfoMatrices.Length; ++i)
{
frameInfoPropertyBlock.SetColor(colorID, frameInfoColors[i]);
Graphics.DrawMesh(quadMesh, parentLocalToWorldMatrix * frameInfoMatrices[i], defaultMaterial, 0, null, 0, frameInfoPropertyBlock, false, false, false);
}
}
}
// Update memory statistics.
if (ShouldShowProfiler && memoryStatsVisible)
{
ulong limit = AppMemoryUsageLimit;
if (limit != limitMemoryUsage)
{
if (WillDisplayedMemoryUsageDiffer(limitMemoryUsage, limit, displayedDecimalDigits))
{
MemoryUsageToString(stringBuffer, displayedDecimalDigits, limitMemoryText, limitMemoryString, limit);
}
limitMemoryUsage = limit;
}
ulong usage = AppMemoryUsage;
if (usage != memoryUsage)
{
usedAnchor.localScale = new Vector3((float)usage / limitMemoryUsage, usedAnchor.localScale.y, usedAnchor.localScale.z);
if (WillDisplayedMemoryUsageDiffer(memoryUsage, usage, displayedDecimalDigits))
{
MemoryUsageToString(stringBuffer, displayedDecimalDigits, usedMemoryText, usedMemoryString, usage);
}
memoryUsage = usage;
}
if (memoryUsage > peakMemoryUsage)
{
peakAnchor.localScale = new Vector3((float)memoryUsage / limitMemoryUsage, peakAnchor.localScale.y, peakAnchor.localScale.z);
if (WillDisplayedMemoryUsageDiffer(peakMemoryUsage, memoryUsage, displayedDecimalDigits))
{
MemoryUsageToString(stringBuffer, displayedDecimalDigits, peakMemoryText, peakMemoryString, memoryUsage);
}
peakMemoryUsage = memoryUsage;
}
}
// Update visibility state.
window.gameObject.SetActive(ShouldShowProfiler);
memoryStats.gameObject.SetActive(memoryStatsVisible);
}
}
19
Source : RealTimePerformanceDemoView.xaml.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void Start()
{
if (!_running)
{
EnableInteractivity(false);
_running = true;
_stopWatch.Start();
_timer = new Timer(TimerInterval);
_timer.Elapsed += OnTick;
_timer.AutoReset = true;
_timer.Start();
}
sciChart.InvalidateElement();
}
19
Source : RateMonitor.cs
with GNU Affero General Public License v3.0
from ACEmulator
with GNU Affero General Public License v3.0
from ACEmulator
public void Resume()
{
stopwatch.Start();
}
19
Source : SolarAnalysisManager.cs
with GNU Lesser General Public License v3.0
from acnicholas
with GNU Lesser General Public License v3.0
from acnicholas
public static void CreateTestFaces(IList<Reference> faceSelection, IList<Reference> mreplacedSelection, double replacedysysGridSize, UIDoreplacedent uidoc, View view)
{
double totalUVPoints = 0;
double totalUVPointsWith2PlusHours = 0;
if (faceSelection == null) {
return;
}
var testFaces = CreateEmptyTestFaces(faceSelection, uidoc.Doreplacedent);
var stopwatch = new Stopwatch();
stopwatch.Start();
// not required when using ReferenceIntersector
var solids = SolidsFromReferences(mreplacedSelection, uidoc.Doreplacedent);
// create a ReferenceIntersection
var ids = mreplacedSelection.Select(s => s.ElementId).ToList();
var referenceIntersector = new ReferenceIntersector(ids, FindReferenceTarget.All, view as View3D);
Transaction t = new Transaction(uidoc.Doreplacedent);
t.Start("testSolarVectorLines");
////create colour scheme
SolarreplacedysisColourSchemes.CreatereplacedysisScheme(SolarreplacedysisColourSchemes.DefaultColours, uidoc.Doreplacedent, "Direct Sunlight Hours", true);
var schemeId = SolarreplacedysisColourSchemes.CreatereplacedysisScheme(SolarreplacedysisColourSchemes.DefaultColours, uidoc.Doreplacedent, "Direct Sunlight Hours - No Legend", false);
foreach (DirectSunTestFace testFace in testFaces) {
var boundingBox = testFace.Face.GetBoundingBox();
double boundingBoxUTotal = boundingBox.Max.U - boundingBox.Min.U;
double boundingBoxVTotal = boundingBox.Max.V - boundingBox.Min.V;
double gridDivisionsU = boundingBoxUTotal > 2 * replacedysysGridSize ? (boundingBoxUTotal / replacedysysGridSize) : 2;
double gridDivisionsV = boundingBoxVTotal > 2 * replacedysysGridSize ? (boundingBoxVTotal / replacedysysGridSize) : 2;
double gridSizeU = boundingBoxUTotal / gridDivisionsU;
double gridSizeV = boundingBoxVTotal / gridDivisionsV;
for (double u = boundingBox.Min.U + (gridSizeU / 2); u <= boundingBox.Max.U; u += gridSizeU) {
for (double v = boundingBox.Min.V + (gridSizeV / 2); v <= boundingBox.Max.V; v += gridSizeV) {
UV uv = new UV(u, v);
if (testFace.Face.IsInside(uv)) {
SunAndShadowSettings setting = view.SunAndShadowSettings;
double interval = 1;
switch (setting.TimeInterval)
{
case SunStudyTimeInterval.Hour:
interval = 1;
break;
case SunStudyTimeInterval.Minutes30:
interval = 0.5;
break;
case SunStudyTimeInterval.Minutes15:
interval = 0.25;
break;
case SunStudyTimeInterval.Minutes45:
interval = 0.75;
break;
}
var hoursOfSun = (setting.NumberOfFrames - 1) * interval;
//// Autodesk makes active frame starts from 1..
for (int activeFrame = 1; activeFrame <= setting.NumberOfFrames; activeFrame++) {
setting.ActiveFrame = activeFrame;
var start = testFace.Face.Evaluate(uv);
start = start.Add(testFace.Face.ComputeNormal(uv).Normalize() / 16);
var sunDirection = GetSunDirectionalVector(uidoc.ActiveView, GetProjectPosition(uidoc.Doreplacedent), out var _);
var end = start.Subtract(sunDirection.Multiply(1000));
//// use this only for testing.
//// BuildingCoder.Creator.CreateModelLine(uidoc.Doreplacedent, start, end);
var line = Line.CreateBound(start, end);
// Brute Force
// remove if ReferenceIntersector is faster...
foreach (var solid in solids)
{
try
{
var solidInt = solid.IntersectWithCurve(line, new SolidCurveIntersectionOptions());
if (solidInt.SegmentCount > 0)
{
hoursOfSun = hoursOfSun - interval;
break;
}
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
}
}
}
totalUVPoints++;
if (hoursOfSun >= 2)
{
totalUVPointsWith2PlusHours++;
}
testFace.AddValueAtPoint(uv, hoursOfSun);
////dump to file
////string path = @"c:\temp\UVHours.txt";
////using (StreamWriter sw = File.AppendText(path))
////{
//// sw.WriteLine(uv.U + "," + uv.V + "," + hoursOfSun);
////}
}
}
}
}
var sfm = DirectSunTestFace.GetSpatialFieldManager(uidoc.Doreplacedent);
sfm.Clear();
foreach (var testFace in testFaces) {
testFace.CreatereplacedysisSurface(uidoc, sfm);
}
view.replacedysisDisplayStyleId = schemeId;
t.Commit();
stopwatch.Stop();
var percent = totalUVPointsWith2PlusHours / totalUVPoints * 100;
var percentString = percent.ToString();
SCaddinsApp.WindowManager.ShowMessageBox("Summary", "Time elepsed " + stopwatch.Elapsed.ToString() + @"(hh:mm:ss:uu), Percent above 2hrs: " + percentString);
}
19
Source : EventHost4.cs
with MIT License
from ad313
with MIT License
from ad313
private async Task CreateRpcService2()
{
_eventBusProvider.RpcServer<int>("aaa", async data =>
{
await Task.CompletedTask;
//throw new Exception($"error in {data}");
//await Task.Delay(5000);
return new RpcResult($"aaa from {data}");
});
await Task.Delay(2000);
Console.WriteLine($"begin---");
var watch = Stopwatch.StartNew();
watch.Start();
var w2 = Stopwatch.StartNew();
for (int i = 0; i < 1; i++)
{
w2.Restart();
var result = await _eventBusProvider.RpcClientAsync<string>("aaa", new object[] { i });
Console.WriteLine($"{result.Data}--{i} {w2.ElapsedMilliseconds}");
}
w2.Stop();
//var tasks1 = Enumerable.Range(0, 10).Select(i => Task.Run(async () =>
//{
// var result = await _eventBusProvider.RpcClientAsync("aaa", i);
// Console.WriteLine($"{result.Data}--{i}");
//})).ToList();
//watch.Start();
//Task.WaitAll(tasks1.ToArray());
watch.Stop();
Console.WriteLine($"end {watch.ElapsedMilliseconds}");
}
19
Source : MainWindow.cs
with MIT License
from adainrivers
with MIT License
from adainrivers
private async Task ProcessImage(Image image)
{
StatusBarLabel1.Text = $"Processing...";
var stopwatch = new Stopwatch();
stopwatch.Start();
await ParseImage(image);
//SetPreviewImage(image);
StatusBarLabel1.Text = $"Processed in {stopwatch.ElapsedMilliseconds} ms.";
if (!HighPerformanceMode.Checked)
{
PerformanceGrid.DataSource = PerformanceProfiler.Current.GetProfiles().Select(pp =>
new
{
Profile = pp.Key,
TotalMS = Math.Round(pp.Value.TotalMilliseconds * 100) / 100,
AverageMS = Math.Round(pp.Value.AverageMilliseconds * 100) / 100,
pp.Value.ExecutionsCount
}).OrderByDescending(a => a.TotalMS).ToList();
}
PerformanceProfiler.Current = new PerformanceProfiler();
}
19
Source : DefaultExecutor.cs
with MIT License
from adamtiger
with MIT License
from adamtiger
public SequentialModelData GetSummary()
{
// Measure time of execution.
double executionTime = 0.0;
Random r = new Random(2);
initInput.ApplyToAll(p => { return r.NextDouble(); });
Stopwatch clock = new Stopwatch();
clock.Start();
Execute(initInput);
clock.Stop();
executionTime = clock.ElapsedMilliseconds;
// Query data of layers.
SequentialModelData seqModelData = new SequentialModelData(executionTime);
foreach(var layer in layers)
{
seqModelData.Add(layer.GetLayerSummary());
}
return seqModelData;
}
19
Source : HandleMessageTest.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[ReleaseModeTheory]
[InlineData(1, 1000, 10000)]
[InlineData(2, 1000, 7500)]
[InlineData(4, 1000, 5000)]
[InlineData(1, 100, 1500)]
[InlineData(2, 100, 1000)]
[InlineData(4, 100, 750)]
public void When_JobHandledCalledWithParallel__ResponseTimeShouldNotExceed(int concurrentJobCount, int times, int expectedMilliseconds)
{
List<Task> tasks = new List<Task>();
for (var i = 0; i < times; i++)
{
DummyMessage dummyMessage = new DummyMessage
{
Guid = Guid.NewGuid()
};
var task = _messageStorageClient.AddMessageAsync(dummyMessage);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<Task> jobProcessorTasks = new List<Task>();
for (var i = 0; i < concurrentJobCount; i++)
{
Task task = Task.Run(async () =>
{
bool jobHandled;
do
{
jobHandled = await _jobDispatcher.HandleNextJobAsync();
} while (jobHandled);
}
);
jobProcessorTasks.Add(task);
}
Task.WaitAll(jobProcessorTasks.ToArray());
stopwatch.Stop();
string message = $"Parallel Job Count : {concurrentJobCount}{Environment.NewLine}" +
$"Executed Job Count : {times}{Environment.NewLine}" +
$"Expected Execution Time : {expectedMilliseconds} ms{Environment.NewLine}" +
$"Actual Execution Time : {stopwatch.ElapsedMilliseconds} ms";
replacedertThat.LessThan(expectedMilliseconds, stopwatch.ElapsedMilliseconds, message);
_output.WriteLine(message);
}
19
Source : AddMessageTest.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[ReleaseModeTheory]
[InlineData(2000, 20000)]
[InlineData(1000, 10000)]
[InlineData(100, 1000)]
public void When_AddMessageCalled__ResponseTimeShouldNotExceed(int times, int expectedMilliseconds)
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<Task> tasks = new List<Task>();
for (int i = 0; i < times; i++)
{
DummyMessage dummyMessage = new DummyMessage()
{
Guid = Guid.NewGuid()
};
var task = _messageStorageClient.AddMessageAsync(dummyMessage);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
stopwatch.Stop();
string message = $"Expected Execution Time : {expectedMilliseconds} ms{Environment.NewLine}" +
$"Actual Execution Time : {stopwatch.ElapsedMilliseconds} ms";
replacedertThat.LessThan(expectedMilliseconds, stopwatch.ElapsedMilliseconds, message);
_output.WriteLine(message);
}
19
Source : HandleMessageTest.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[ReleaseModeTheory]
[InlineData(1, 1000, 10000)]
[InlineData(2, 1000, 7500)]
[InlineData(4, 1000, 5000)]
[InlineData(1, 100, 1500)]
[InlineData(2, 100, 1000)]
[InlineData(4, 100, 750)]
public void When_JobHandledCalledWithParallel__ResponseTimeShouldNotExceed(int parallelJobCount, int times, int expectedMilliseconds)
{
List<Task> addTasks = new List<Task>();
for (var i = 0; i < times; i++)
{
DummyMessage dummyMessage = new DummyMessage
{
Guid = Guid.NewGuid()
};
var task = _messageStorageClient.AddMessageAsync(dummyMessage);
addTasks.Add(task);
}
Task.WaitAll(addTasks.ToArray());
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
List<Task> jobProcessorTasks = new List<Task>();
for (var i = 0; i < parallelJobCount; i++)
{
Task task = Task.Run(async () =>
{
bool jobHandled;
do
{
jobHandled = await _jobDispatcher.HandleNextJobAsync();
} while (jobHandled);
}
);
jobProcessorTasks.Add(task);
}
Task.WaitAll(jobProcessorTasks.ToArray());
stopwatch.Stop();
string message = $"Parallel Job Count : {parallelJobCount}{Environment.NewLine}" +
$"Executed Job Count : {times}{Environment.NewLine}" +
$"Expected Execution Time : {expectedMilliseconds} ms{Environment.NewLine}" +
$"Actual Execution Time : {stopwatch.ElapsedMilliseconds} ms";
replacedertThat.LessThan(expectedMilliseconds, stopwatch.ElapsedMilliseconds, message);
_output.WriteLine(message);
}
19
Source : JobDispatcher_HandleNextJobAsync_Test.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[Fact]
public void WhenParallelJobIsAllowed__TasksShouldNotWaitEachOther()
{
TimeSpan jobConsumeTime = TimeSpan.FromSeconds(5);
const int jobCount = 8;
List<Task> addTasks = new List<Task>();
for (var i = 0; i < jobCount; i++)
{
LongProcessRequest longProcessRequest = new LongProcessRequest(jobConsumeTime);
var task = _messageStorageClient.AddMessageAsync(longProcessRequest);
addTasks.Add(task);
}
Task.WaitAll(addTasks.ToArray());
var stopwatch = new Stopwatch();
stopwatch.Start();
List<Task> jobProcessorTasks = new List<Task>();
for (var i = 0; i < jobCount; i++)
{
var handleTask = _jobDispatcher.HandleNextJobAsync();
jobProcessorTasks.Add(handleTask);
}
Task.WaitAll(jobProcessorTasks.ToArray());
stopwatch.Stop();
double threshold = jobConsumeTime.TotalMilliseconds * 1.5;
_output.WriteLine($"Threshold : {threshold} ms -- Actual execution time : {stopwatch.ElapsedMilliseconds} ms");
replacedertThat.LessThan(threshold, stopwatch.ElapsedMilliseconds);
}
19
Source : JobDispatcher_HandleNextJobAsync_Test.cs
with MIT License
from AdemCatamak
with MIT License
from AdemCatamak
[Fact]
public void WhenParallelJobIsAllowed__TasksShouldNotWaitEachOther()
{
TimeSpan jobConsumeTime = TimeSpan.FromSeconds(5);
const int jobCount = 8;
List<Task> addTasks = new List<Task>();
for (var i = 0; i < jobCount; i++)
{
LongProcessRequest longProcessRequest = new LongProcessRequest(jobConsumeTime);
var task = _messageStorageClient.AddMessageAsync(longProcessRequest);
addTasks.Add(task);
}
Task.WaitAll(addTasks.ToArray());
var stopwatch = new Stopwatch();
stopwatch.Start();
List<Task> jobProcessorTasks = new List<Task>();
for (var i = 0; i < jobCount; i++)
{
var handleTask = _sut.HandleNextJobAsync();
jobProcessorTasks.Add(handleTask);
}
Task.WaitAll(jobProcessorTasks.ToArray());
stopwatch.Stop();
double threshold = jobConsumeTime.TotalMilliseconds * 1.5;
_output.WriteLine($"Threshold : {threshold} ms -- Actual execution time : {stopwatch.ElapsedMilliseconds} ms");
replacedertThat.LessThan(threshold, stopwatch.ElapsedMilliseconds);
}
19
Source : PortalFacetedIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected override RawSearchResultSet GetRawSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int offset)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var br = new BrowseRequest();
br.Count = searchLimit;
br.Sort = this.GetSortField(query);
br.Query = this.CreateQuery(query);
br.Offset = offset;
this.AddFacetConstraints(br, query.FacetConstraints);
// add preconfigured facet specs
foreach (var fieldToSpec in this.specs)
{
br.SetFacetSpec(fieldToSpec.Key, fieldToSpec.Value);
}
// execute the query
IBrowsable browser = new BoboBrowser(this.boboReader);
foreach (var facetConfiguration in this.config.GetConfiguredFacets())
{
if (facetConfiguration.FacetHandlerType == FacetHandlerType.Dynamic)
{
browser.SetFacetHandler(facetConfiguration.FacetHandler);
}
}
var browseResult = browser.Browse(br);
stopwatch.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Lucene(faceted/BoboBrowse): {0} total hits ({1}ms)", browseResult.NumHits, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, browseResult.NumHits, stopwatch.ElapsedMilliseconds, string.Format("Lucene(faceted/BoboBrowse): {0} total hits ({1}ms)", browseResult.NumHits, stopwatch.ElapsedMilliseconds));
return this.ConvertBoboBrowseResultsToRawSearchResultSet(browseResult, offset, query.FacetConstraints);
}
19
Source : CrmEntityIndexBuilder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private void UpdateWithIndexers(string enreplacedyLogicalName, IEnumerable<ICrmEnreplacedyIndexer> indexers)
{
if (!indexers.Any(indexer => indexer.Indexes(enreplacedyLogicalName)))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Application does not index enreplacedy {0}. No update performed.", enreplacedyLogicalName));
return;
}
var enreplacedyIndexDoreplacedents = indexers.SelectMany(indexer => indexer.GetDoreplacedents()).ToArray();
UsingWriter(MethodBase.GetCurrentMethod().Name, false, true, writer =>
{
foreach (var enreplacedyDoc in enreplacedyIndexDoreplacedents)
{
writer.DeleteDoreplacedents(GetEnreplacedyQuery(_index, enreplacedyLogicalName, enreplacedyDoc.PrimaryKey));
}
});
int currentIndex = 0;
while (currentIndex < enreplacedyIndexDoreplacedents.Length)
{
UsingWriter(MethodBase.GetCurrentMethod().Name, false, true, writer =>
{
var stopwatch = new Stopwatch();
stopwatch.Start();
for (; currentIndex < enreplacedyIndexDoreplacedents.Length; currentIndex++)
{
writer.AddDoreplacedent(enreplacedyIndexDoreplacedents[currentIndex].Doreplacedent, enreplacedyIndexDoreplacedents[currentIndex].replacedyzer);
// We've held onto the write lock too long, there might be other updates waiting on us.
// Release the lock so they don't time out, then re-enter the queue for the write lock.
if (stopwatch.Elapsed.TotalSeconds > 10)
{
// break;
}
}
});
}
}
19
Source : CrmEntityIndexBuilder.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual void UsingWriter(string description, bool create, bool optimize, Action<IndexWriter> action)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0}: Start", description));
var stopwatch = new Stopwatch();
stopwatch.Start();
try
{
var retryPolicy = new RetryPolicy(new LockObtainTransientErrorDetectionStrategy(), 25, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(2));
using (var writer = retryPolicy.ExecuteAction(() => new IndexWriter(_index.Directory, _index.replacedyzer, create, IndexWriter.MaxFieldLength.UNLIMITED)))
{
try
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0}: Acquired write lock, writing", description));
action(writer);
if (optimize)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0}: Optimizing index", description));
writer.Optimize();
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceWarning(TraceCategory.Application, string.Format("{0}: Error during index write: rollback, rethrow: {1}", description, e));
writer.Rollback();
throw;
}
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0}: Index writer closed", description));
}
catch (Exception e)
{
SearchEventSource.Log.WriteError(e);
throw;
}
finally
{
stopwatch.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0}: End (Elapsed time: {1})", description, stopwatch.Elapsed));
}
}
19
Source : CrmEntityIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected virtual RawSearchResultSet GetRawSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int rawOffset)
{
var stopwatch = new Stopwatch();
stopwatch.Start();
var luceneQuery = CreateQuery(query);
TopDocs topDocs;
try
{
topDocs = _searcher.Search(luceneQuery, searchLimit);
}
catch (Exception e)
{
SearchEventSource.Log.QueryError(e);
throw;
}
stopwatch.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Lucene: {0} total hits ({1}ms)", topDocs.TotalHits, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, topDocs.TotalHits, stopwatch.ElapsedMilliseconds, string.Format("Lucene: {0} total hits ({1}ms)", topDocs.TotalHits, stopwatch.ElapsedMilliseconds));
return ConvertTopDocsToRawSearchResultSet(topDocs, rawOffset);
}
19
Source : CrmEntityIndexSearcher.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
protected ICrmEnreplacedySearchResultPage GetUserSearchResults(ICrmEnreplacedyQuery query, int searchLimit, int initialOffset, int resultLimit, ICrmEnreplacedySearchResultFactory resultFactory, int pageNumber, int pageSize, ICollection<ICrmEnreplacedySearchResult> results)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("(searchLimit={0},rawOffset={1},resultLimit={2})", searchLimit, initialOffset, resultLimit));
RawSearchResultSet rawSearchResults = GetRawSearchResults(query, searchLimit, initialOffset);
if (initialOffset >= rawSearchResults.TotalHits)
{
return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
}
var stopwatch = new Stopwatch();
stopwatch.Start();
var groupedNotes = new List<IGrouping<EnreplacedyReference, ICrmEnreplacedySearchResult>>();
var displayNotes = IsAnnotationSearchEnabled();
if (displayNotes && !string.IsNullOrEmpty(query.QueryTerm))
{
var rawNotes = this.GetRelatedAnnotations(rawSearchResults, query);
var notes =
rawNotes.Select(doreplacedent => resultFactory.GetResult(doreplacedent, 1, results.Count + 1)).ToList();
//Grouping Notes by related Knowledge Articles
groupedNotes =
notes.Where(note => note.EnreplacedyLogicalName == "annotation")
.GroupBy(note => note.Enreplacedy.GetAttributeValue<EnreplacedyReference>("objectid"))
.ToList();
}
var offsetForNexreplacederation = initialOffset;
foreach (var scoreDoc in rawSearchResults.Results)
{
offsetForNexreplacederation++;
var result = resultFactory.GetResult(_searcher.Doc(scoreDoc.Doc), scoreDoc.Score, results.Count + 1);
// Not a valid user result, filter out
if (result == null)
{
continue;
}
if (result.EnreplacedyLogicalName == "knowledgearticle" && displayNotes)
{
var relatedNotes = groupedNotes.Where(a => a.Key.Id == result.EnreplacedyID).SelectMany(i => i).Take(3).ToList();
if (relatedNotes.Any(note => note.Fragment == result.Fragment))
{
result.Fragment = GetKnowledgeArticleDescription(result);
}
result.Enreplacedy["relatedNotes"] = relatedNotes;
}
results.Add(result);
if (results.Count >= resultLimit)
{
stopwatch.Stop();
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("Gathered {0} results, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GenerateResultPage(results, rawSearchResults.TotalHits, pageNumber, pageSize, rawSearchResults);
}
}
stopwatch.Stop();
// We asked for more hits than we got back from Lucene, and we still didn't gather enough valid
// results. That's all we're going to get, so the number of results we got is the number of hits.
if (searchLimit >= rawSearchResults.TotalHits)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("All available results ({0}) gathered, done ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GenerateResultPage(results, results.Count, pageNumber, pageSize, rawSearchResults);
}
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
PortalFeatureTrace.TraceInstance.LogSearch(FeatureTraceCategory.Search, results.Count, stopwatch.ElapsedMilliseconds, string.Format("{0} results gathered so far ({1}ms)", results.Count, stopwatch.ElapsedMilliseconds));
return GetUserSearchResults(query, searchLimit * ExtendedSearchLimitMultiple, offsetForNexreplacederation, resultLimit, resultFactory, pageNumber, pageSize, results);
}
See More Examples