本文整理汇总了C#中System.Diagnostics.Stopwatch类的典型用法代码示例。如果您正苦于以下问题:C# Stopwatch类的具体用法?C# Stopwatch怎么用?C# Stopwatch使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Stopwatch类属于System.Diagnostics命名空间,在下文中一共展示了Stopwatch类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: ModelVisual3D
// Add all cubes to a ModelVisual3D, reuse geometry but create new visual for each cube - this is slow
/* GeometryModel3D AddGeometrySeparate(IEnumerable<Point3D> centers, double L)
{
var mv = new ModelVisual3D();
var cubit = new CubeVisual3D { SideLength = L * 0.95, Fill = Brushes.Gold };
var cuboidGeometry = cubit.Model.Geometry as MeshGeometry3D;
var r = new Random();
foreach (var center in centers)
{
var tg = new Transform3DGroup();
tg.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(1, 0, 0), (r.NextDouble() - 0.5) * 10)));
tg.Children.Add(new RotateTransform3D(new AxisAngleRotation3D(new Vector3D(0, 1, 0), (r.NextDouble() - 0.5) * 10)));
tg.Children.Add(new TranslateTransform3D(center.ToVector3D()));
var c = new ModelVisual3D
{
Content =
new GeometryModel3D
{
Geometry = cuboidGeometry,
Material = cubit.Material,
Transform = tg
}
};
mv.Children.Add(c);
}
return mv;
}*/
// All cubes in one GeometryModel - much faster
GeometryModel3D AddGeometry(IEnumerable<Point3D> centers, double L)
{
var w = new Stopwatch();
w.Start();
/* var geometry = new MeshGeometry3D();
foreach (var center in centers)
{
MeshGeometryHelper.AddBox(geometry,center, L, L, L);
}
*/
var builder = new MeshBuilder();
foreach (var center in centers)
{
builder.AddBox(center, L, L, L);
}
var geometry = builder.ToMesh();
geometry.Freeze();
Trace.WriteLine(Level + ": " + w.ElapsedMilliseconds + " ms");
var mv = new GeometryModel3D
{
Geometry = geometry,
Material = MaterialHelper.CreateMaterial(Brushes.Gold)
};
TriangleCount = geometry.TriangleIndices.Count / 3;
return mv;
}
开发者ID:XiBeichuan,项目名称:hydronumerics,代码行数:62,代码来源:MengerSponge.cs
示例2: DailyMaintenance
public async Task<ActionResult> DailyMaintenance(string key)
{
Stopwatch stopWatch = new Stopwatch();
// Cleanse the passed string parameters to prevent XSS.
string cleanKey = Server.HtmlEncode(key);
if (cleanKey == doctrineShipsServices.Settings.TaskKey)
{
// Time the execution of the daily maintenance.
stopWatch.Reset();
stopWatch.Start();
// Run daily maintenance tasks.
await this.doctrineShipsServices.DailyMaintenance();
// Stop the clock.
stopWatch.Stop();
logger.LogMessage("Daily Maintenance Successful, Time Taken: " + stopWatch.Elapsed, 2, "Message", MethodBase.GetCurrentMethod().Name);
return Content("Daily Maintenance Successful, Time Taken: " + stopWatch.Elapsed);
}
else
{
logger.LogMessage("Daily Maintenance Failed, Invalid Key: " + cleanKey, 1, "Message", MethodBase.GetCurrentMethod().Name);
return Content("Daily Maintenance Failed, Invalid Key");
}
}
开发者ID:jameswlong,项目名称:doctrineships,代码行数:28,代码来源:TaskController.cs
示例3: Solution2
public static int Solution2(Stopwatch timer)
{
timer.Restart();
var a = new HashSet<int>();
int maxlcm = 1;
int t = 0;
var results = new List<int>();
for (int i = 2; i <= 20; i++)
{
int k = i%2 == 0 ? 1 : 2;
for (int j = k; j < i; j+=2)
{
if (gcd(i, j) == 1)
{
a.Add(2*i*(i + j));
}
}
}
var sortedA = a.OrderBy(v => v).ToArray();
while (maxlcm < 1000)
{
maxlcm = lcm(maxlcm, sortedA[t]);
results.Add(maxlcm);
t++;
}
int res = results[results.Count - 2];
timer.Stop();
return res;
}
开发者ID:joce,项目名称:EulerProject,代码行数:34,代码来源:Problem039.cs
示例4: SetUp
public void SetUp()
{
var stopwatch = new Stopwatch();
_pack = new ConventionPack();
_pack.AddRange(new IConvention[]
{
new TrackingBeforeConvention(stopwatch) { Name = "1" },
new TrackingMemberConvention(stopwatch) { Name = "3" },
new TrackingAfterConvention(stopwatch) { Name = "5" },
new TrackingMemberConvention(stopwatch) { Name = "4" },
new TrackingAfterConvention(stopwatch) { Name = "6" },
new TrackingBeforeConvention(stopwatch) { Name = "2" },
});
_subject = new ConventionRunner(_pack);
var classMap = new BsonClassMap<TestClass>(cm =>
{
cm.MapMember(t => t.Prop1);
cm.MapMember(t => t.Prop2);
});
stopwatch.Start();
_subject.Apply(classMap);
stopwatch.Stop();
}
开发者ID:niemyjski,项目名称:mongo-csharp-driver,代码行数:25,代码来源:ConventionRunnerTests.cs
示例5: GenerateMetadata
public TemplateGenerationMetadata GenerateMetadata()
{
var timer = new Stopwatch();
timer.Start();
// load the templates we'll be generating into a state storage collection
var templateData = CreateTemplateData();
foreach (var template in templateData.Templates)
{
HashSet<string> fieldKeys = GetBaseFieldSet(); // get fields on base type
fieldKeys.Add(template.TypeName); // member names cannot be the same as their enclosing type so we add the type name to the fields collection
foreach (var baseTemplate in template.Template.AllNonstandardBaseTemplates) // similarly names can't be the same as any of their base templates' names (this would cause an incompletely implemented interface)
{
if (templateData.Contains(baseTemplate.TemplateId))
{
fieldKeys.Add(templateData[baseTemplate.TemplateId].TypeName);
}
else fieldKeys.Add(baseTemplate.Name.AsIdentifier()); // NOTE: you could break this if you have a base template called Foo and a field called Foo that IS NOT on the Foo template (but why would you have that?)
}
// generate item properties
foreach (var field in template.Template.Fields)
{
if (_templateInputProvider.IsFieldIncluded(field.Id)) // query the template input provider and make sure the field is included
{
string propertyName = field.Name.AsNovelIdentifier(fieldKeys);
var fieldInfo = new FieldPropertyInfo(field);
fieldInfo.FieldPropertyName = propertyName;
fieldInfo.SearchFieldName = _indexFieldNameTranslator.GetIndexFieldName(field.Name);
fieldInfo.FieldType = _fieldMappingProvider.GetFieldType(field);
if (fieldInfo.FieldType == null)
{
Log.Warn("Synthesis: Field type resolution for " + field.Template.Name + "::" + field.Name + " failed; no mapping found for field type " + field.Type, this);
continue; // skip adding the field for generation
}
// record usage of the property name
fieldKeys.Add(propertyName);
// add the field to the metadata
template.FieldsToGenerate.Add(fieldInfo);
}
}
// generates interfaces to represent the Sitecore template inheritance hierarchy
TemplateInfo baseInterface = GenerateInheritedInterfaces(template.Template, templateData);
if (baseInterface != null)
template.InterfacesImplemented.Add(baseInterface);
}
timer.Stop();
Log.Info(string.Format("Synthesis: Generated metadata for {0} concrete templates and {1} interface templates in {2} ms", templateData.Templates.Count, templateData.Interfaces.Count, timer.ElapsedMilliseconds), this);
return templateData;
}
开发者ID:BerserkerDotNet,项目名称:Synthesis,代码行数:60,代码来源:MetadataGenerator.cs
示例6: should_be_faster_than_the_fcl_json_deserializer
public void should_be_faster_than_the_fcl_json_deserializer()
{
var json = "[" + Enumerable.Range(0, 5).Select(x => "{" +
"\"Value0\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
"\"Value1\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
"\"Value2\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
"\"Value3\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ], " +
"\"Value4\": [ " + Enumerable.Range(0, 5).Select(y => "{ \"Value0\": \"ssdfsfsfd\", \"Value1\": \"sfdsfsdf\", \"Value2\": \"adasd\", \"Value3\": \"wqerqwe\", \"Value4\": \"qwerqwer\" }").Aggregate((a, i) => a + "," + i) + " ] " +
"}").Aggregate((a, i) => a + ", " + i) + "]";
var stopwatch = new Stopwatch();
stopwatch.Start();
for (var i = 0; i < 100; i++) Bender.Deserializer.Create().DeserializeJson<List<SpeedTestCollection>>(json);
stopwatch.Stop();
var benderSpeed = stopwatch.ElapsedTicks;
var jsonSerializer = new JavaScriptSerializer();
stopwatch.Start();
for (var i = 0; i < 100; i++) jsonSerializer.Deserialize<List<SpeedTestCollection>>(json);
stopwatch.Stop();
var javascriptSerializerSpeed = stopwatch.ElapsedTicks;
Debug.WriteLine("Bender speed (ticks): {0:#,##0}", benderSpeed);
Debug.WriteLine("JavaScriptSerializer speed (ticks): {0:#,##0}", javascriptSerializerSpeed);
(benderSpeed < javascriptSerializerSpeed).ShouldBeTrue();
}
开发者ID:ChrisMissal,项目名称:Bender,代码行数:27,代码来源:PerformanceTests.cs
示例7: Dequeue
//https://github.com/rabbitmq/rabbitmq-tutorials/blob/master/dotnet/Worker/Worker.cs
static void Dequeue(string queueName, string hostName, int expected)
{
int count = 0;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
var factory = new ConnectionFactory() { HostName = hostName };
factory.UserName = "rabbit";
factory.Password = "password";
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queueName, true, false, false, null);
channel.BasicQos(0, 1, false);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume(queueName, false, consumer);
sw.Start();
while (count < expected)
{
BasicDeliverEventArgs ea = consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
channel.BasicAck(ea.DeliveryTag, false);
++count;
}
sw.Stop();
}
}
Console.WriteLine(" [x] {0} messages dequeued in time = {1} ms", count, sw.ElapsedMilliseconds);
}
开发者ID:udaparts,项目名称:socketpro,代码行数:30,代码来源:Program.cs
示例8: Invoke
public async Task Invoke(HttpContext context)
{
var sw = new Stopwatch();
sw.Start();
using (var memoryStream = new MemoryStream())
{
var bodyStream = context.Response.Body;
context.Response.Body = memoryStream;
await _next(context);
var isHtml = context.Response.ContentType?.ToLower().Contains("text/html");
if (context.Response.StatusCode == 200 && isHtml.GetValueOrDefault())
{
memoryStream.Seek(0, SeekOrigin.Begin);
using (var streamReader = new StreamReader(memoryStream))
{
var responseBody = await streamReader.ReadToEndAsync();
//C# 6 DEMO
var newFooter = string.Format($"<footer><div id='process'>Page processed in {sw.ElapsedMilliseconds} milliseconds.</div>");
responseBody = responseBody.Replace("<footer>", newFooter);
context.Response.Headers.Add("X-ElapsedTime", new[] { sw.ElapsedMilliseconds.ToString() });
using (var amendedBody = new MemoryStream())
using (var streamWriter = new StreamWriter(amendedBody))
{
streamWriter.Write(responseBody);
amendedBody.Seek(0, SeekOrigin.Begin);
await amendedBody.CopyToAsync(bodyStream);
}
}
}
}
}
开发者ID:jmhumblet,项目名称:TheBBQProject,代码行数:34,代码来源:TimingMiddleware.cs
示例9: Search
public ISearchResult Search(string query)
{
var timer = new Stopwatch();
timer.Start();
var directory = FSDirectory.Open(new DirectoryInfo(path));
var analyzer = new StandardAnalyzer(Version.LUCENE_29);
var searcher = new IndexSearcher(directory, true);
var queryParser = new QueryParser(Version.LUCENE_29, "text", analyzer);
var result = searcher.Search(queryParser.Parse(query), 20);
var docs = (from scoreDoc in result.scoreDocs
let doc = searcher.Doc(scoreDoc.doc)
let fields = new Dictionary<string, string> { { "title", doc.Get("title") }, { "text", doc.Get("text") } }
select new LuceneDocument { Id = scoreDoc.doc.ToString(), Fields = fields }).ToList();
var ret = new SearchResult { Query = query, Total = result.totalHits, Documents = docs, Source = Name };
searcher.Close();
directory.Close();
timer.Stop();
ret.Duration = (decimal) timer.Elapsed.TotalSeconds;
return ret;
}
开发者ID:billings-dot-net-users-group,项目名称:search-demo,代码行数:27,代码来源:LuceneIndex.cs
示例10: PerformanceRemoveRoom_With5000RemoveCommands_With10000BunniesIn5000Rooms
public void PerformanceRemoveRoom_With5000RemoveCommands_With10000BunniesIn5000Rooms()
{
for (int i = 0; i < 5000; i++)
{
this.BunnyWarCollection.AddRoom(i);
}
for (int i = 0; i < 10000; i++)
{
this.BunnyWarCollection.AddBunny(i.ToString(), i % 5, i / 2);
}
//Arrange
var count = 5000;
var roomsCount = 5000;
//Act
Stopwatch timer = new Stopwatch();
timer.Start();
for (int i = 0; i < roomsCount; i++)
{
this.BunnyWarCollection.Remove(i);
Assert.AreEqual(--count, this.BunnyWarCollection.RoomCount, "Incorrect count of rooms after removal!");
}
timer.Stop();
Assert.IsTrue(timer.ElapsedMilliseconds < 400);
}
开发者ID:vangelov-i,项目名称:Fundamentals,代码行数:27,代码来源:RemovePerformance.cs
示例11: SocketTestClient
public SocketTestClient(
ITestOutputHelper log,
string server,
int port,
int iterations,
string message,
Stopwatch timeProgramStart)
{
_log = log;
_server = server;
_port = port;
_endpoint = new DnsEndPoint(server, _port);
_sendString = message;
_sendBuffer = Encoding.UTF8.GetBytes(_sendString);
_bufferLen = _sendBuffer.Length;
_recvBuffer = new byte[_bufferLen];
_timeProgramStart = timeProgramStart;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // on Unix, socket will be created in Socket.ConnectAsync
{
_timeInit.Start();
_s = new Socket(SocketType.Stream, ProtocolType.Tcp);
_timeInit.Stop();
}
_iterations = iterations;
}
开发者ID:dotnet,项目名称:corefx,代码行数:31,代码来源:SocketTestClient.cs
示例12: DeltaTime
/// <summary>
/// new DeltaTime object
/// </summary>
public DeltaTime()
{
m_manualDt = false;
m_dt = 0;
m_timer = new Stopwatch();
m_timer.Start();
}
开发者ID:shockwave4488,项目名称:CSharpRoboticsLib,代码行数:10,代码来源:DeltaTime.cs
示例13: Configuration
public void Configuration(IAppBuilder app)
{
app.Run(context =>
{
Stopwatch stopWatch = new Stopwatch();
Trace.WriteLine("Received client call. Starting stop watch now.");
stopWatch.Start();
context.Request.CallCancelled.Register(() =>
{
stopWatch.Stop();
Trace.WriteLine(string.Format("Cancellation token triggered. Elapsed time : {0}. Test should succeed", stopWatch.Elapsed));
NotificationServer.NotifyClient();
});
int retryCount = 0;
while (retryCount < 3)
{
Thread.CurrentThread.Join(5 * 1000);
if (context.Request.CallCancelled.IsCancellationRequested)
{
break;
}
retryCount++;
}
return context.Response.WriteAsync("FAILURE");
});
}
开发者ID:Xamarui,项目名称:Katana,代码行数:29,代码来源:OwinCallCancelledTest.cs
示例14: Stopwatch
/// <summary>
/// Wrap a stopwatch aroudn the execution of an action.
/// </summary>
/// <param name="handler">The action to be timed.</param>
/// <returns>Time elapsed during the handler's execution.</returns>
public static TimeSpan Stopwatch(Action handler) {
var s = new Diagnostics.Stopwatch();
s.Start();
handler();
s.Stop();
return s.Elapsed;
}
开发者ID:nataren,项目名称:DReAM,代码行数:12,代码来源:DebugUtil.cs
示例15: Should_fail_to_resolve_route_because_it_does_have_an_invalid_condition
public void Should_fail_to_resolve_route_because_it_does_have_an_invalid_condition()
{
// Given
var cache = new FakeRouteCache(with => {
with.AddGetRoute("/invalidcondition", "modulekey", ctx => false);
});
var bootstrapper = new ConfigurableBootstrapper(with =>{
with.RouteCache(cache);
});
var browser = new Browser(bootstrapper);
// When
var timer = new Stopwatch();
timer.Start();
for (var i = 0; i < numberOfTimesToResolveRoute; i++)
{
var result = browser.Get("/invalidcondition");
result.StatusCode.ShouldEqual(HttpStatusCode.NotFound);
}
timer.Stop();
// Then
Debug.WriteLine(" took {0} to execute {1} times", timer.Elapsed, numberOfTimesToResolveRoute);
}
开发者ID:felbus,项目名称:Nancy,代码行数:28,代码来源:DefaultRouteResolverPerformanceFixture.cs
示例16: Opened
// public methods
public void Opened()
{
_stopwatch = Stopwatch.StartNew();
_appPackage.CurrentNumberOfOpenConnections.Increment();
_serverPackage.CurrentNumberOfOpenConnections.Increment();
}
开发者ID:mfidemraizer,项目名称:mongo-csharp-driver,代码行数:8,代码来源:ConnectionPerformanceRecorder.cs
示例17: Thirty
public void Thirty()
{
TestContext.DeleteAll(x => x.Entity_Basics);
TestContext.Insert(x => x.Entity_Basics, 50);
using (var ctx = new TestContext())
{
// BEFORE
Assert.AreEqual(1225, ctx.Entity_Basics.Sum(x => x.ColumnInt));
// ACTION
var clock = new Stopwatch();
clock.Start();
var rowsAffected = ctx.Entity_Basics.Where(x => x.ColumnInt > 10 && x.ColumnInt <= 40).Update(x => new Entity_Basic { ColumnInt = 99 }, update =>
{
update.BatchDelayInterval = 50;
update.BatchSize = 5;
});
clock.Stop();
// AFTER
Assert.AreEqual(460, ctx.Entity_Basics.Sum(x => x.ColumnInt));
Assert.AreEqual(30, rowsAffected);
Assert.IsTrue(clock.ElapsedMilliseconds > 250 && clock.ElapsedMilliseconds < 600);
}
}
开发者ID:emmatb1,项目名称:EntityFramework-Plus,代码行数:26,代码来源:FiftyMilliseconds.cs
示例18: TraceAttributeContext
public TraceAttributeContext(string traceId, string methodId, string parentMethodId)
{
TraceId = traceId;
MethodId = methodId;
ParentMethodId = parentMethodId;
Stopwatch = Stopwatch.StartNew();
}
开发者ID:csuzw,项目名称:Tracer,代码行数:7,代码来源:TraceAttributeContext.cs
示例19: BulkMerge
public static void BulkMerge(int nbRecords, Stopwatch clock, StringBuilder sb)
{
int recordsToUpdate = nbRecords/2;
int recordsToInsert = nbRecords - recordsToUpdate;
var listToInsert = new List<EntitySimple>();
for (int i = 0; i < recordsToInsert; i++)
{
listToInsert.Add(new EntitySimple {ColumnInt = i%5});
}
using (var ctx = new CodeFirstEntities())
{
ctx.EntitySimples.AddRange(listToInsert);
List<EntitySimple> listToUpdate = ctx.EntitySimples.Take(recordsToUpdate).AsNoTracking().ToList();
listToUpdate.ForEach(x => x.ColumnInt = x.ColumnInt + 1);
sb.Append(string.Format("INSERT {0} / UPDATE {1} entities", recordsToInsert, recordsToUpdate));
clock.Start();
ctx.BulkMerge(listToUpdate);
clock.Stop();
}
}
开发者ID:reckcn,项目名称:Z.EntityFramework.Extensions,代码行数:26,代码来源:BulkMerge.cs
示例20: Inverse
public void Inverse()
{
var stopWatch = new Stopwatch();
stopWatch.Start();
var csgA = new CSG.CSG();
csgA.Construct(A.GetComponent<MeshFilter>().sharedMesh, A.transform, 0);
var substract = csgA.Inverse();
var newMesh = substract.ToMesh();
Result = new GameObject("Inverse");
var defObj = Result.AddComponent<DefaultObject>();
var meshFilter = Result.AddComponent<MeshFilter>();
meshFilter.sharedMesh = newMesh;
var renderer = Result.AddComponent<MeshRenderer>();
renderer.sharedMaterial = new Material(A.GetComponent<MeshRenderer>().sharedMaterial);
if (DeleteOriginal)
{
Object.DestroyImmediate(A);
}
stopWatch.Stop();
defObj.GenerationTimeMS = stopWatch.ElapsedMilliseconds;
}
开发者ID:jfeng94,项目名称:Thesis,代码行数:26,代码来源:BooleanOp.cs
注:本文中的System.Diagnostics.Stopwatch类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论