Exportar (0) Imprimir
Expandir todo

Stopwatch.ElapsedMilliseconds (Propiedad)

Actualización: noviembre 2007

Obtiene el tiempo transcurrido total medido por la instancia actual, en milisegundos.

Espacio de nombres:  System.Diagnostics
Ensamblado:  System (en System.dll)

public long ElapsedMilliseconds { get; }
/** @property */
public long get_ElapsedMilliseconds()

public function get ElapsedMilliseconds () : long

Valor de propiedad

Tipo: System.Int64
Un entero largo de sólo lectura que representa el número total de milisegundos medido por la instancia actual.

Esta propiedad representa el tiempo transcurrido redondeado hacia abajo al milisegundo entero más próximo al valor. Para realizar mediciones de precisión superior, utilice las propiedades Elapsed o ElapsedTicks.

Puede consultar las propiedades Elapsed, ElapsedMilliseconds y ElapsedTicks mientras la instancia de Stopwatch se está ejecutando o cuando está detenida. Las propiedades de tiempo transcurrido aumentan continuamente mientras se ejecuta Stopwatch; permanecen constantes cuando la instancia está detenida.

De manera predeterminada, el valor de tiempo transcurrido de una instancia de Stopwatch es igual al total de todos los intervalos de tiempo medidos. Cada llamada a Start inicia la cuenta del tiempo transcurrido acumulado; cada llamada a Stop finaliza la medición del intervalo actual y bloquea el valor de tiempo transcurrido acumulado. Utilice el método Reset para borrar el tiempo transcurrido acumulado en una instancia de Stopwatch existente.

En el ejemplo siguiente se utiliza la clase Stopwatch para medir el rendimiento de cuatro implementaciones diferentes para analizar un entero procedente de una cadena.

private static void TimeOperations()
{
    long nanosecPerTick = (1000L*1000L*1000L) / Stopwatch.Frequency;
    const long numIterations = 10000;

    // Define the operation title names.
    String [] operationNames = {"Operation: Int32.Parse(\"0\")",
                                   "Operation: Int32.TryParse(\"0\")",
                                   "Operation: Int32.Parse(\"a\")",
                                   "Operation: Int32.TryParse(\"a\")"};


    // Time four different implementations for parsing 
    // an integer from a string. 

    for (int operation = 0; operation <= 3; operation++)
    {
        // Define variables for operation statistics.
        long numTicks = 0;
        long numRollovers = 0;
        long maxTicks = 0;
        long minTicks = Int64.MaxValue;
        int indexFastest = -1;
        int indexSlowest = -1;
        long milliSec = 0;

        Stopwatch time10kOperations = Stopwatch.StartNew();

        // Run the current operation 10001 times.
        // The first execution time will be tossed
        // out, since it can skew the average time.

        for (int i=0; i<=numIterations; i++) 
        {
            long ticksThisTime = 0;
            int inputNum;
            Stopwatch timePerParse;

            switch (operation)
            {
                case 0:
                    // Parse a valid integer using
                    // a try-catch statement.

                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    try 
                    {
                        inputNum = Int32.Parse("0");
                    }
                    catch (FormatException)
                    {
                        inputNum = 0;
                    }

                    // Stop the timer, and save the
                    // elapsed ticks for the operation.

                    timePerParse.Stop();
                    ticksThisTime = timePerParse.ElapsedTicks;
                    break;
                case 1:
                    // Parse a valid integer using
                    // the TryParse statement.

                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    if (!Int32.TryParse("0", out inputNum))
                    { 
                        inputNum = 0;
                    }

                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.ElapsedTicks;
                    break;
                case 2:
                    // Parse an invalid value using
                    // a try-catch statement.

                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    try 
                    {
                        inputNum = Int32.Parse("a");
                    }
                    catch (FormatException)
                    {
                        inputNum = 0;
                    }

                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.ElapsedTicks;
                    break;
                case 3:
                    // Parse an invalid value using
                    // the TryParse statement.

                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    if (!Int32.TryParse("a", out inputNum))
                    { 
                        inputNum = 0;
                    }

                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.ElapsedTicks;
                    break;

                default:
                    break;
            }

            // Skip over the time for the first operation,
            // just in case it caused a one-time
            // performance hit.
            if (i == 0)
            {
                time10kOperations.Reset();
                time10kOperations.Start();
            }
            else 
            {

                // Update operation statistics
                // for iterations 1-10001.
                if (maxTicks < ticksThisTime)
                {
                    indexSlowest = i;
                    maxTicks = ticksThisTime;
                }
                if (minTicks > ticksThisTime)
                {
                    indexFastest = i;
                    minTicks = ticksThisTime;
                }
                numTicks += ticksThisTime;
                if (numTicks < ticksThisTime)
                {
                    // Keep track of rollovers.
                    numRollovers ++;
                }
            }
        }  

        // Display the statistics for 10000 iterations.

        time10kOperations.Stop();
        milliSec = time10kOperations.ElapsedMilliseconds;

        Console.WriteLine();
        Console.WriteLine("{0} Summary:", operationNames[operation]);
        Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks",
            indexSlowest, numIterations, maxTicks);
        Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks",
            indexFastest, numIterations, minTicks);
        Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds", 
            numTicks / numIterations, 
            (numTicks * nanosecPerTick) / numIterations );
        Console.WriteLine("  Total time looping through {0} operations: {1} milliseconds", 
            numIterations, milliSec);
    }
}


private static void TimeOperations()
{
    long nanoSecPerTick = (1000L * 1000L * 1000L) / Stopwatch.Frequency;
    final long numIterations = 10000;

    // Define the operation title names.
    String operationNames[] =  { "Operation: Int32.Parse(\"0\")", 
        "Operation: Int32.TryParse(\"0\")", "Operation: Int32.Parse(\"a\")",
        "Operation: Int32.TryParse(\"a\")" };

    // Time four different implementations for parsing 
    // an integer from a string. 
    for (int operation = 0; operation <= 3; operation++) {
        // Define variables for operation statistics.
        long numTicks = 0;
        long numRollovers = 0;
        long maxTicks = 0;
        long minTicks = Int64.MaxValue;
        int indexFastest = -1;
        int indexSlowest = -1;
        long milliSec = 0;

        Stopwatch time10kOperations = Stopwatch.StartNew();
        // Run the current operation 10001 times.
        // The first execution time will be tossed
        // out, since it can skew the average time.
        for (int i = 0; i <= numIterations; i++) {
            long ticksThisTime = 0;
            int inputNum = 0;
            Stopwatch timePerParse;

            switch (operation) {
                case 0:
                    // Parse a valid integer using
                    // a try-catch statement.
                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    try {
                        inputNum = Int32.Parse("0");
                    }
                    catch (FormatException exp) {
                        inputNum = 0;
                    }
                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.get_ElapsedTicks();
                    break;

                case 1:
                    // Parse a valid integer using
                    // the TryParse statement.
                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    if (!(Int32.TryParse("0", inputNum))) {
                        inputNum = 0;
                    }
                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.get_ElapsedTicks();
                    break;

                case 2:
                    // Parse an invalid value using
                    // a try-catch statement.
                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    try {
                        inputNum = Int32.Parse("a");
                    }
                    catch (FormatException exp) {
                        inputNum = 0;
                    }
                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.get_ElapsedTicks();
                    break;

                case 3:
                    // Parse an invalid value using
                    // the TryParse statement.
                    // Start a new stopwatch timer.
                    timePerParse = Stopwatch.StartNew();

                    if (!(Int32.TryParse("a", inputNum))) {
                        inputNum = 0;
                    }
                    // Stop the timer, and save the
                    // elapsed ticks for the operation.
                    timePerParse.Stop();
                    ticksThisTime = timePerParse.get_ElapsedTicks();
                    break;

                default:
                    break;
            }
            // Skip over the time for the first operation,
            // just in case it caused a one-time
            // performance hit.
            if (i == 0) {
                time10kOperations.Reset();
                time10kOperations.Start();
            }
            else {
                // Update operation statistics
                // for iterations 1-10001.
                if (maxTicks < ticksThisTime) {
                    indexSlowest = i;
                    maxTicks = ticksThisTime;
                }
                if (minTicks > ticksThisTime) {
                    indexFastest = i;
                    minTicks = ticksThisTime;
                }
                numTicks += ticksThisTime;
                if (numTicks < ticksThisTime) {
                    // Keep track of rollovers.
                    numRollovers++;
                }
            }
        }
        // Display the statistics for 10000 iterations.
        time10kOperations.Stop();
        milliSec = time10kOperations.get_ElapsedMilliseconds();

        Console.WriteLine();
        Console.WriteLine("{0} Summary:", 
            operationNames.get_Item(operation));
        Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks", 
            (Int32)indexSlowest, (Int64)numIterations, (Int64)maxTicks);
        Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks", 
            (Int32)indexFastest, (Int64)numIterations, (Int64)minTicks);
        Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds", 
            (System.Double)(numTicks / numIterations), 
            (System.Double)(numTicks * nanoSecPerTick / numIterations));
        Console.WriteLine("  Total time looping through {0} operations: "
            + "{1} milliseconds", (Int64)numIterations, (Int64)milliSec);
    }
} //TimeOperations 


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0

.NET Compact Framework

Compatible con: 3.5

XNA Framework

Compatible con: 2.0, 1.0

Adiciones de comunidad

AGREGAR
Mostrar:
© 2014 Microsoft