C# tips and tricks 31 - Measure Execution Time using Stopwatch | How to find task execution time?

Опубликовано: 04 Октябрь 2024
на канале: Ankpro Training
6,389
60

How to measure task execution time?
What is Stopwatch?
How to find task execution time?

What is Stopwatch?
A Stopwatch instance can measure elapsed time for one interval, or the total of elapsed time across multiple intervals.

Namespace is System.Diagnostics

Stopwatch Properties
Elapsed
ElapsedMilliseconds
ElapsedTicks
IsRunning

Stopwatch Methods
Equals()
GetTimestamp()
MemberWiseClone()
Reset()
Restart()
Start()
StartNew()
Stop()

Stop watch demo code :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace StopwatchDemo
{
class Program
{
static void Main(string[] args)
{
var watch = Stopwatch.StartNew();

for (int i = 0; i lessthan 1000; i++)
{
Console.WriteLine(i +"\n");
}

watch.Stop();

Console.WriteLine($"Execution time :{ watch.ElapsedMilliseconds}ms");


var sw = Stopwatch.StartNew();
long ticks = sw.ElapsedTicks;
Console.WriteLine(ticks);

Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
stopwatch.Stop();
TimeSpan ts = stopwatch.Elapsed;
Console.WriteLine(ts);
}
}
}