🧭Stopwatch
El Stopwatch es una herramienta de .NET que permite medir el tiempo que tarda en ejecutarse un fragmento de código.
🛠️ Cómo usar Stopwatch
Agregar el espacio de nombres: Primero, necesitas agregar el espacio de nombres System.Diagnostics
para poder usar Stopwatch
.
using System.Diagnostics;
Crear una instancia de Stopwatch: Puedes crear un Stopwatch utilizando el método StartNew()
o el constructor new Stopwatch()
y luego iniciarlo con Start()
.
Stopwatch stopwatch = Stopwatch.StartNew(); // Inicia automáticamente
// o
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start(); // Iniciar manualmente
Ejecutar el código que quieres medir: Coloca el código cuyo tiempo de ejecución quieres medir entre el Start()
y Stop()
.
stopwatch.Start();
// Tu código aquí
stopwatch.Stop();
Leer el tiempo transcurrido: Puedes obtener el tiempo transcurrido en diferentes unidades, como milisegundos, segundos o ticks (1 tick = 100 nanosegundos).
Console.WriteLine($"Tiempo transcurrido en milisegundos: {stopwatch.ElapsedMilliseconds}ms");
Console.WriteLine($"Tiempo transcurrido en ticks: {stopwatch.ElapsedTicks}");
🚨 Consideraciones
Precisión: La precisión de
Stopwatch
puede variar según el hardware en el que se ejecute.Overhead: Aunque pequeño,
Stopwatch
agrega un overhead al tiempo de ejecución.
🧪 Ejemplo
using System.Diagnostics;
class Program
{
static void Main()
{
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < 1000000; i++)
{
// Simula trabajo
}
stopwatch.Stop();
Console.WriteLine($"Tiempo transcurrido: {stopwatch.ElapsedMilliseconds}ms");
}
}
Última actualización