내보내기(0) 인쇄
모두 확장

Stopwatch.ElapsedMilliseconds 속성

업데이트: 2007년 11월

현재 인스턴스가 측정한 밀리초 단위의 총 경과 시간을 가져옵니다.

네임스페이스:  System.Diagnostics
어셈블리:  System(System.dll)

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

public function get ElapsedMilliseconds () : long

속성 값

형식: System.Int64

현재 인스턴스가 측정한 총 밀리초 수를 나타내는 읽기 전용 long integer입니다.

이 속성은 경과 시간을 가장 가까운 정수 밀리초 값으로 나머지 버림 처리하여 나타냅니다. 측정의 정밀도를 높이려면 Elapsed 또는 ElapsedTicks 속성을 사용합니다.

Stopwatch 인스턴스가 실행 중이거나 중지된 동안 Elapsed, ElapsedMillisecondsElapsedTicks 속성을 쿼리할 수 있습니다. 경과 시간 속성은 Stopwatch가 실행 중인 동안에는 꾸준히 증가하고 해당 인스턴스가 중지되면 일정하게 유지됩니다.

기본적으로 Stopwatch 인스턴스의 경과 시간 값은 측정된 모든 시간 간격 합계와 같습니다. Start를 호출할 때마다 누적 경과 시간에서 시간 계산이 시작됩니다. Stop을 호출할 때마다 현재 간격 측정이 종료되고 누적 경과 시간 값은 고정됩니다. Reset 메서드를 사용하여 기존 Stopwatch 인스턴스에서 누적 경과 시간을 지울 수 있습니다.

다음 예제에서는 Stopwatch 클래스를 사용하여 문자열에서 정수를 구문 분석하는 네 가지 구현 방법의 성능을 측정합니다.

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 for Smartphone, Windows Mobile for Pocket PC, Xbox 360

.NET Framework 및 .NET Compact Framework에서 모든 플랫폼의 전체 버전을 지원하지는 않습니다. 지원되는 버전의 목록을 보려면 .NET Framework 시스템 요구 사항을 참조하십시오.

.NET Framework

3.5, 3.0, 2.0에서 지원

.NET Compact Framework

3.5에서 지원

XNA Framework

2.0, 1.0에서 지원

커뮤니티 추가 항목

추가
표시:
© 2014 Microsoft