本文整理汇总了C#中System.Diagnostics.Stopwatch.Stop方法的典型用法代码示例。如果您正苦于以下问题:C# System.Diagnostics.Stopwatch.Stop方法的具体用法?C# System.Diagnostics.Stopwatch.Stop怎么用?C# System.Diagnostics.Stopwatch.Stop使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Diagnostics.Stopwatch
的用法示例。
在下文中一共展示了System.Diagnostics.Stopwatch.Stop方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: button1_Click
private void button1_Click(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
var ControllerIPAddress = new IPAddress(new byte[] { 192, 168, 0, 2 });
var ControllerPort = 40001;
var ControllerEndPoint = new IPEndPoint(ControllerIPAddress, ControllerPort);
_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var header = "@";
var command = "00C";
var checksum = "E3";
var end = "\r\n";
var data = header + command + checksum + end;
byte[] bytes = new byte[1024];
//Start Connect
_connectDone.Reset();
watch.Start();
_client.BeginConnect(ControllerIPAddress, ControllerPort, new AsyncCallback(ConnectCallback), _client);
//wait 2s
_connectDone.WaitOne(2000, false);
var text = (_client.Connected) ? "ok" : "ng";
richTextBox1.AppendText(text + "\r\n");
watch.Stop();
richTextBox1.AppendText("Consumer time: " + watch.ElapsedMilliseconds + "\r\n");
}
示例2: MeasureStopwatch
public void MeasureStopwatch()
{
var sw = new System.Diagnostics.Stopwatch();
var measured = new System.Diagnostics.Stopwatch();
sw.Reset();
sw.Start();
measured.Start();
measured.Stop();
var warmupTemp = measured.ElapsedMilliseconds;
sw.Stop();
var warmupTime = sw.ElapsedMilliseconds;
measured.Reset();
sw.Reset();
sw.Start();
sw.Stop();
var originalTime = sw.ElapsedMilliseconds;
sw.Reset();
sw.Start();
for (var i = 0; i < 1000000; i++)
{
measured.Start();
measured.Stop();
var temp = measured.ElapsedMilliseconds;
}
sw.Stop();
var measuredTime = sw.ElapsedMilliseconds;
Console.WriteLine(measuredTime - originalTime);
}
示例3: button2_Click
private void button2_Click(object sender, EventArgs e)
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
label3.Text = "???ms";
label4.Text = "Total is ";
richTextBox1.Text = "";
sw.Reset();
sw.Start();
List<int> resultList = primeNumbers.LinearSieve((int)numericUpDown1.Value, (int)numericUpDown2.Value);
sw.Stop();
label3.Text = (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
label4.Text = "Total is " + resultList.Count;
sw.Start();
string a = string.Join(",", resultList.ToArray());
//sw.Stop();
//Console.WriteLine((sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString());
richTextBox1.Invoke((MethodInvoker)delegate {
//sw.Reset();
//sw.Start();
richTextBox1.AppendText(a);
sw.Stop();
label3.Text = label3.Text + "/" + (sw.Elapsed.TotalMilliseconds.ToString() + " ms").ToString();
}
);
}
示例4: Main
static void Main(string[] args)
{
string s = System.IO.File.ReadAllText(@"example.json");
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
for (int i = 0; i < 10000; i++)
Fairytale.JsonDeserializer.Deserialize(s);
sw.Stop();
Console.WriteLine(sw.Elapsed);
sw.Reset();
sw.Start();
for (int i = 0; i < 10000; i++)
Newtonsoft.Json.JsonConvert.DeserializeObject(s);
sw.Stop();
Console.WriteLine(sw.Elapsed);
sw.Reset();
sw.Start();
var parser = new System.Text.Json.JsonParser();
for (int i = 0; i < 10000; i++)
parser.Parse(s);
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.ReadLine();
}
示例5: TestFromTxtFile
public void TestFromTxtFile(string file)
{
var wordUtil = new WordDict();
var expectWordCount = 0;
using (var sr = new StreamReader(file, Encoding.UTF8))
{
string line = null;
while ((line = sr.ReadLine()) != null)
{
if (line == string.Empty) continue;
wordUtil.Add(line);
expectWordCount++;
}
}
var watcher = new System.Diagnostics.Stopwatch();
watcher.Start();
var ms = new MemoryStream();
wordUtil.SaveTo(ms);
watcher.Stop();
Console.WriteLine("build dawg elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");
watcher.Reset();
watcher.Start();
ms.Position = 0;
wordUtil = WordDict.LoadFrom(ms);
watcher.Stop();
Console.WriteLine("load dawg file elapsed time:" + watcher.Elapsed.TotalMilliseconds + "'ms");
Assert.AreEqual(expectWordCount, wordUtil.Count);
}
示例6: Brute
static void Brute(string target, string letters, string algorithm, int start, int end)
{
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
Query.Letters = letters;
Query.size = start;
for (var query = new Query(); query.Length <= end; query.Next())
{
var hash = Invoke("brute", "Program", algorithm, new object[]
{
query.ToString()
});
if (hash.Equals(target))
{
Console.WriteLine("" + query.ToString() + " is Correct!!\n");
Console.WriteLine("[*] " + target + " is " + query.ToString());
sw.Stop();
Console.WriteLine(sw.Elapsed);
return;
}
Console.WriteLine(query.ToString() + " is Not Correct...");
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
Console.WriteLine("[*] Not Found...");
}
示例7: TestExecuteIntersectionQuery
public void TestExecuteIntersectionQuery()
{
NUnit.Framework.Assert.IsTrue(System.IO.File.Exists(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp")),
"Specified shapefile is not present!");
var shp = new SharpMap.Data.Providers.ShapeFile(GetTestDataFilePath("SPATIAL_F_SKARVMUFF.shp"), false, false);
shp.Open();
var fds = new SharpMap.Data.FeatureDataSet();
var bbox = shp.GetExtents();
//narrow it down
bbox.ExpandBy(-0.425*bbox.Width, -0.425*bbox.Height);
//Just to avoid that initial query does not impose performance penalty
shp.DoTrueIntersectionQuery = false;
shp.ExecuteIntersectionQuery(bbox, fds);
fds.Tables.RemoveAt(0);
//Perform query once more
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
shp.ExecuteIntersectionQuery(bbox, fds);
sw.Stop();
System.Console.WriteLine("Queried using just envelopes:\n" + fds.Tables[0].Rows.Count + " in " +
sw.ElapsedMilliseconds + "ms.");
fds.Tables.RemoveAt(0);
shp.DoTrueIntersectionQuery = true;
sw.Reset();
sw.Start();
shp.ExecuteIntersectionQuery(bbox, fds);
sw.Stop();
System.Console.WriteLine("Queried using prepared geometries:\n" + fds.Tables[0].Rows.Count + " in " +
sw.ElapsedMilliseconds + "ms.");
}
示例8: Search
private static void Search(int collectionSize, int searchItemsCount)
{
Console.WriteLine($"V množině o velikost {collectionSize:n0} hledáno {searchItemsCount:n0}x:");
#region Sample data
var sw = new System.Diagnostics.Stopwatch();
var list = new List<Guid>();
var dictionary = new Dictionary<Guid, object>();
foreach (var guid in Enumerable.Range(0, collectionSize).Select(g => Guid.NewGuid()))
{
list.Add(guid);
dictionary.Add(guid, null);
}
var lookup = list.ToLookup(i => i);
var sortedArray = list.ToArray();
Array.Sort(sortedArray);
// vytvoření sample-dat, které budeme hledat
var rand = new Random();
var hledane = Enumerable.Range(0, searchItemsCount).Select(g => (rand.NextDouble() > 0.5) ? Guid.NewGuid() : list[rand.Next(list.Count)]).ToList();
#endregion
// Contains = sekvenční vyhledávání = O(n)
sw.Start();
int found = hledane.Count(t => list.Contains(t));
sw.Stop();
Console.WriteLine($"\tList<>.Contains(): Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");
// binární půlení = O(log(n))
sw.Restart();
found = hledane.Count(t => Array.BinarySearch<Guid>(sortedArray, t) >= 0);
sw.Stop();
Console.WriteLine($"\tArray.BinarySearch<>(): Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");
// Dictionary = Hashtable, O(1)
sw.Restart();
found = hledane.Count(t => dictionary.ContainsKey(t));
sw.Stop();
Console.WriteLine($"\tDictionary<>.ContainsKey(): Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");
// Dictionary = Hashtable, O(1)
sw.Restart();
found = hledane.Count(i => lookup.Contains(i));
sw.Stop();
Console.WriteLine($"\tLINQ ILookup: Nalezeno {found:n0}x, čas {sw.ElapsedTicks,10:n0} ticks");
Console.WriteLine();
}
示例9: TestWarpedLineSymbolizer
public void TestWarpedLineSymbolizer()
{
var p = new SharpMap.Data.Providers.ShapeFile(@"d:\\daten\GeoFabrik\\Aurich\\roads.shp", false);
var l = new SharpMap.Layers.VectorLayer("roads", p);
var cls = new SharpMap.Rendering.Symbolizer.CachedLineSymbolizer();
cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.PlainLineSymbolizeHandler { Line = new System.Drawing.Pen(System.Drawing.Color.Gold, 2) });
cls.LineSymbolizeHandlers.Add(new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander { Pattern = SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetGreaterSeries(3, 3), Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1) });
l.Style.LineSymbolizer = cls;
var m = new SharpMap.Map(new System.Drawing.Size(720, 540)) {BackColor = System.Drawing.Color.Cornsilk};
m.Layers.Add(l);
m.ZoomToExtents();
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
var bmp = m.GetMap();
sw.Stop();
System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
bmp.Save("AurichRoads1.bmp");
cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
{
Pattern = SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetTriangleSeries(4, 7),
Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
};
sw.Start();
bmp = m.GetMap();
sw.Stop();
System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
bmp.Save("AurichRoads2.bmp");
//cls.LineSymbolizeHandlers[0] = cls.LineSymbolizeHandlers[1];
cls.LineSymbolizeHandlers[1] = new SharpMap.Rendering.Symbolizer.WarpedLineSymbolizeHander
{
Pattern = SharpMap.Rendering.Symbolizer.WarpedLineSymbolizer.GetZigZag(4, 4),
Line = new System.Drawing.Pen(System.Drawing.Color.Firebrick, 1),
//Fill = new System.Drawing.SolidBrush(System.Drawing.Color.Firebrick)
};
sw.Start();
bmp = m.GetMap();
sw.Stop();
System.Console.WriteLine(string.Format("Rendering new method: {0}ms", sw.ElapsedMilliseconds));
bmp.Save("AurichRoads3.bmp");
}
示例10: acceptIncomingConnection
static void acceptIncomingConnection(IAsyncResult ar)
{
Socket mainsock = (Socket)ar.AsyncState;
Socket incomingsock = mainsock.EndAccept(ar);
Donify.Set();
System.Diagnostics.Stopwatch swatch = new System.Diagnostics.Stopwatch();
swatch.Start();
logger.log("Got connection from: " + incomingsock.RemoteEndPoint, Logging.Priority.Notice);
if (socketfunctions.waitfordata(incomingsock, 10000, true))
{
string[] incomingstring = socketfunctions.receivestring(incomingsock, true).Replace("\r\n", "\n").Split('\n');
try
{
string response = bstuff.OnyEvents.NewMessage(incomingstring, (IPEndPoint)incomingsock.RemoteEndPoint);
logger.log("got from plugins: " + response, Logging.Priority.Notice);
if (response == null || response == "")
socketfunctions.sendstring(incomingsock, "Blargh.");
else
socketfunctions.sendstring(incomingsock, response);
}
catch (Exception ex)
{ logger.logerror(ex); }
incomingsock.Shutdown(SocketShutdown.Both);
incomingsock.Close();
swatch.Stop();
logger.log("Session time: " + swatch.ElapsedMilliseconds, Logging.Priority.Info);
bstuff.OnyVariables.amountloops++;
}
}
示例11: SetUp
protected void SetUp()
{
base_cycle_metric_header header = new base_cycle_metric_header();
if(metrics.Count == 0)
{
System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
float[] focus1 = new float[]{2.24664021f, 2.1896739f, 0, 0};
ushort[] p90_1 = new ushort[]{302, 273, 0, 0};
for(uint lane = 1;lane <=8;lane++)
{
for(uint tile = 1;tile <=TileCount;tile++)
{
for(uint cycle = 1;cycle <=318;cycle++)
{
metrics.Add(new extraction_metric(lane, tile, cycle, new csharp_date_time(9859129975844165472ul), (p90_1), (focus1), 4));
}
}
}
extraction_metric_set = new base_extraction_metrics(metrics, Version, header);
timer.Stop();
System.Console.WriteLine("Setup: " + timer.Elapsed.Hours +" : " + timer.Elapsed.Minutes +" : " + timer.Elapsed.Seconds);
System.Console.WriteLine("Size: " + metrics.Count + " - " + extraction_metric_set.size());
}
}
示例12: WorkerEvents
static private void WorkerEvents()
{
Tuple<EventDelegate, Effect, Effect> cEvent;
System.Diagnostics.Stopwatch cWatch = new System.Diagnostics.Stopwatch();
while (true)
{
try
{
cEvent = _aqEvents.Dequeue();
cWatch.Reset();
cWatch.Restart();
cEvent.Item1(cEvent.Item2, cEvent.Item3);
(new Logger()).WriteDebug3("event sended [hc = " + cEvent.Item3.GetHashCode() + "][" + cEvent.Item1.Method.Name + "]");
cWatch.Stop();
if (40 < cWatch.ElapsedMilliseconds)
(new Logger()).WriteDebug3("duration: " + cWatch.ElapsedMilliseconds + " queue: " + _aqEvents.nCount);
if (0 < _aqEvents.nCount)
(new Logger()).WriteDebug3(" queue: " + _aqEvents.nCount);
}
catch (System.Threading.ThreadAbortException)
{
break;
}
catch (Exception ex)
{
(new Logger()).WriteError(ex);
}
}
}
示例13: Given_A_Checklist_Is_Being_Saved_Then_Returns_Status_OK
public void Given_A_Checklist_Is_Being_Saved_Then_Returns_Status_OK()
{
// Given
var client = new RestClient(Url.AbsoluteUri);
client.Authenticator = new NtlmAuthenticator( "continuous.int","is74rb80pk52" );
const int numberOfRequestsToSend = 15;
var stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
var parallelLoopResult = Parallel.For(0, numberOfRequestsToSend, x =>
{
//GIVEN
var model = CreateChecklistViewModel();
var resourceUrl = string.Format("{0}{1}/{2}", ApiBaseUrl, "checklists", model.Id.ToString());
var request = new RestRequest(resourceUrl);
request.AddHeader("Content-Type", "application/json");
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.AddBody(model);
// When
var response = client.Execute(request);
//THEN
Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
});
stopWatch.Stop();
var processingSeconds = TimeSpan.FromMilliseconds(stopWatch.ElapsedMilliseconds).TotalSeconds;
Assert.That(parallelLoopResult.IsCompleted);
Console.WriteLine(string.Format("average: {0}", processingSeconds / numberOfRequestsToSend));
}
示例14: DevRun
static void DevRun()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
var opts = new Options();
opts.ExecutionMode = ExecutionMode.Serial;
ProtoCore.Core core = new Core(opts);
core.Compilers.Add(ProtoCore.Language.Associative, new ProtoAssociative.Compiler(core));
core.Compilers.Add(ProtoCore.Language.Imperative, new ProtoImperative.Compiler(core));
#if DEBUG
core.Options.DumpByteCode = true;
core.Options.Verbose = true;
#else
core.Options.DumpByteCode = false;
core.Options.Verbose = false;
#endif
ProtoFFI.DLLFFIHandler.Register(ProtoFFI.FFILanguage.CSharp, new ProtoFFI.CSModuleHelper());
ProtoScriptRunner runner = new ProtoScriptRunner();
// Assuming current directory in test/debug mode is "...\Dynamo\bin\AnyCPU\Debug"
runner.LoadAndExecute(@"..\..\..\test\core\dsevaluation\DSFiles\test.ds", core);
long ms = sw.ElapsedMilliseconds;
sw.Stop();
Console.WriteLine(ms);
Console.ReadLine();
}
示例15: Mul
static void Mul(InputData data, Port<int> resp)
{
int i, j;
System.Diagnostics.Stopwatch sWatch = new System.Diagnostics.Stopwatch();
sWatch.Start();
for (i = data.start; i <= data.stop-1; i++)
{
for (j = i+1; j <= data.stop; j++)
{
if (a[j] < a[i]) //сортировка пузырьком
{
var temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
//внимательно присмотревшись к этой функции и к условиям, в которых она вызывается, можно сделать вывод
//что она вернет массив, состоящий из двух сортированных половинок, но не сортированный целиком
//так оно и есть, потому что параллельный пузырек - необычная задумка
//в данной лабораторной работе эта проблема решается в делегате, описанном в приемнике, штатными средствами C#
sWatch.Stop();
resp.Post(1);
Console.WriteLine("Поток № {0}: Параллельный алгоритм = {1} мс.", Thread.CurrentThread.ManagedThreadId, sWatch.ElapsedMilliseconds.ToString());
}