Windows get elapsed time

Stopwatch. Elapsed Свойство

Определение

Получает общее затраченное время, измеренное текущим экземпляром. Gets the total elapsed time measured by the current instance.

Значение свойства

Доступный только для чтения объект TimeSpan, который представляет общее затраченное время, измеренное текущим экземпляром. A read-only TimeSpan representing the total elapsed time measured by the current instance.

Примеры

В следующем примере показано, как использовать Elapsed свойство для определения времени выполнения приложения. The following example demonstrates how to use the Elapsed property to determine the execution time for an application.

Комментарии

В типичном Stopwatch сценарии вызывается Start метод, затем вызывается Stop метод, а затем проверяются затраченное время с помощью Elapsed Свойства. In a typical Stopwatch scenario, you call the Start method, then eventually call the Stop method, and then you check elapsed time using the Elapsed property.

Используйте Elapsed свойство для получения значения затраченного времени с помощью TimeSpan методов и свойств. Use the Elapsed property to retrieve the elapsed time value using TimeSpan methods and properties. Например, можно отформатировать возвращаемый TimeSpan экземпляр в текстовое представление или передать его другому классу, для которого требуется TimeSpan параметр. For example, you can format the returned TimeSpan instance into a text representation, or pass it to another class that requires a TimeSpan parameter.

Можно запрашивать свойства Elapsed , ElapsedMilliseconds и ElapsedTicks во время Stopwatch работы или остановки экземпляра. You can query the properties Elapsed, ElapsedMilliseconds, and ElapsedTicks while the Stopwatch instance is running or stopped. Свойства затраченного времени постоянно увеличиваются во время Stopwatch работы. они остаются постоянными при остановке экземпляра. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.

По умолчанию значение затраченного времени Stopwatch экземпляра равно сумме всех измеренных интервалов времени. By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Каждый вызов начинает подсчитаться Start на совокупное затраченное время; каждый вызов Stop завершает текущую меру интервала и замораживает совокупное значение затраченного времени. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Используйте Reset метод для очистки совокупного истекшего времени в существующем Stopwatch экземпляре. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.

Time Functions

The following functions are used with system time.

Function Description
GetSystemTime Retrieves the current system date and time in UTC format.
GetSystemTimeAdjustment Determines whether the system is applying periodic time adjustments to its time-of-day clock.
GetTimeFormat Formats a system time as a time string for a specified locale.
NtQuerySystemTime Returns the system time.
RtlLocalTimeToSystemTime Converts the specified local time to system time.
RtlTimeToSecondsSince1970 Converts the specified system time to the number of seconds since the first second of January 1, 1970.
SetSystemTime Sets the current system time and date.
SetSystemTimeAdjustment Enables or disables periodic time adjustments to the system’s time-of-day clock.
SystemTimeToFileTime Converts a system time to a file time.
SystemTimeToTzSpecificLocalTime Converts a UTC time to a specified time zone’s corresponding local time.
TzSpecificLocalTimeToSystemTime Converts a local time to a UTC time.

The following functions are used with local time.

Function Description
EnumDynamicTimeZoneInformation Enumerates dynamic daylight saving time information entries stored in the registry.
FileTimeToLocalFileTime Converts a UTC file time to a local file time.
GetDynamicTimeZoneInformation Retrieves the current time zone and dynamic daylight saving time settings.
GetDynamicTimeZoneInformationEffectiveYears Retrieves a range, expressed in years, for which a DYNAMIC_TIME_ZONE_INFORMATION has valid entries.
GetLocalTime Retrieves the current local date and time.
GetTimeZoneInformation Retrieves the current time zone settings.
GetTimeZoneInformationForYear Retrieves the time zone settings for the specified year and time zone.
RtlLocalTimeToSystemTime Converts the specified local time to system time.
SetDynamicTimeZoneInformation Sets the current time zone and dynamic daylight saving time settings.
SetLocalTime Sets the current local time and date.
SetTimeZoneInformation Sets the current time zone settings.
SystemTimeToTzSpecificLocalTime Converts a UTC time to a specified time zone’s corresponding local time.
SystemTimeToTzSpecificLocalTimeEx Converts a UTC time with dynamic daylight saving time settings to a specified time zone’s corresponding local time.
TzSpecificLocalTimeToSystemTime Converts a local time to a UTC time.
TzSpecificLocalTimeToSystemTimeEx Converts a local time with dynamic daylight saving time settings to UTC time.

The following functions are used with file time.

Function Description
CompareFileTime Compares two file times.
FileTimeToLocalFileTime Converts a UTC file time to a local file time.
FileTimeToSystemTime Converts a file time to system time format.
GetFileTime Retrieves the date and time that the specified file or directory was created, last accessed, and last modified.
GetSystemTimeAsFileTime Retrieves the current system date and time in UTC format.
LocalFileTimeToFileTime Converts a local file time to a file time based on UTC.
SetFileTime Sets the date and time that the specified file or directory was created, last accessed, or last modified.
SystemTimeToFileTime Converts a system time to a file time.

The following functions are used with MS-DOS date and time.

Function Description
DosDateTimeToFileTime Converts MS-DOS date and time values to a file time.
FileTimeToDosDateTime Converts a file time to MS-DOS date and time values.

The following functions are used with Windows time.

Function Description
GetSystemTimes Retrieves system timing information.
GetTickCount Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days.
GetTickCount64 Retrieves the number of milliseconds that have elapsed since the system was started.

The following functions are used with high-resolution performance counters.

Function Description
QueryPerformanceCounter Retrieves the current value of the high-resolution performance counter.
QueryPerformanceFrequency Retrieves the frequency of the high-resolution performance counter.

The following functions are used with the auxiliary performance counter.

Function Description
QueryAuxiliaryCounterFrequency Queries the auxiliary counter frequency.
ConvertAuxiliaryCounterToPerformanceCounter Converts the specified auxiliary counter value to the corresponding performance counter value; optionally provides the estimated conversion error in nanoseconds due to latencies and maximum possible drift.
ConvertPerformanceCounterToAuxiliaryCounter Converts the specified performance counter value to the corresponding auxiliary counter value; optionally provides the estimated conversion error in nanoseconds due to latencies and maximum possible drift.

The following function is used with interrupt time.

Best way to get elapsed time in miliseconds in windows

I’m trying to do it using two FILETIMEs, casting them to ULONGLONGs, substracting the ULONGLONGs, and dividing the result by 10000. But it’s pretty slow, and I want to know if there is a better way to do it.I use c++ with visual studio 2008 express edition. This is what I’m using:

5 Answers 5

Generally timeGetTime() is best for timing game logic — GetTickCount isn’t quite high enough resolution, and QPC & RDTSC are a lot more trouble than they are worth for that purpose.

For profiling on the other hand, either RDTSC or QPC can be quite worthwhile. I prefer RDTSC over QPC, though microsoft recommends QPC.

The four common time functions I use on win32:

GetTickCount() returns the current time in milliseconds relative to some arbitrary zero (usually, though not always system boot time), as a 32 bit integer (so it wraps every 49 days or so). It is usually the fastest method to measure a time. Unfortunately it is low resolution — typically it only updates 64 times per second. Contrary to popular rumor, calling timeBeginPeriod(1) will not increase its resolution on any system I’ve tested that on. There is also a 64 bit variant if you’re worried about it wrapping.

timeGetTime() returns the current time in milliseconds relative to some arbitrary zero, as a 32 bit value (so it wraps after 49 days or so). It’s not as fast as GetTickCount, but still pretty reasonable. It can be accurate to a single millisecond, though that may require calling timeBeginPeriod(1) first. Using timeGetTime requires linking against winmm.lib and including Mmsystem.h.

QueryPerformanceCounter() returns the current time in arbitrary units as a 64 bit integer. You can figure out what the units are by calling QueryPerformanceFrequency(), and the units will not change (absent a reboot). The underlying implementation of this varies widely, and each implementation has its own quirks and bugs that may occur on some hardware, making this obnoxious to use in widely deployed applications. Some implementations are very slow, others are reasonable, though none are as fast as GetTickCount or even timeGetTime. Typically timing resolution is better than 1 microsecond, though not necessarily much better.

RDTSC is an x86 / x64 assembly language opcode that returns the current time in units of CPU cycles (ie as a 64 bit integer. On some compilers it can be accessed as an intrinsic (__rdstc), on others you’ll need inline asm. Its speed varies a bit between CPUs but is usually pretty reasonable — typically significantly faster than QueryPerformanceCounter but not as fast as GetTickCount. Unfortunately it has a few quirks — not as many as QueryPerformanceCounter, but still a lot more than the lower resolution time functions. It can sometimes run backwards on multicore CPUs when you switch cores due to imperfect synchronization between cores, the units are difficult to figure out, and the units can change in mid-timing due to power management changing the rate of the CPU clock.

Note that each of these four methods can drift relative to the other three — there is no clear authoritative flow of time.

Stopwatch. Elapsed Ticks Свойство

Определение

Получает общее затраченное время в тактах таймера, измеренное текущим экземпляром. Gets the total elapsed time measured by the current instance, in timer ticks.

Значение свойства

Доступное только для чтения длинное целое число, представляющее общее число тактов таймера, измеренное текущим экземпляром. A read-only long integer representing the total number of timer ticks measured by the current instance.

Примеры

В следующем примере класс используется Stopwatch для измерения производительности четырех различных реализаций для синтаксического анализа целого числа из строки. The following example uses the Stopwatch class to measure the performance of four different implementations for parsing an integer from a string. Этот пример кода является частью большого примера, приведенного для Stopwatch класса. This code example is part of a larger example provided for the Stopwatch class.

Комментарии

Это свойство представляет количество прошедших тактов в базовом механизме таймера. This property represents the number of elapsed ticks in the underlying timer mechanism. Такт — это наименьшая единица времени, которую Stopwatch может измерять таймер. A tick is the smallest unit of time that the Stopwatch timer can measure. Используйте Frequency поле, чтобы преобразовать ElapsedTicks значение в число секунд. Use the Frequency field to convert the ElapsedTicks value into a number of seconds.

Можно запрашивать свойства Elapsed , ElapsedMilliseconds и ElapsedTicks во время Stopwatch работы или остановки экземпляра. You can query the properties Elapsed, ElapsedMilliseconds, and ElapsedTicks while the Stopwatch instance is running or stopped. Свойства затраченного времени постоянно увеличиваются во время Stopwatch работы. они остаются постоянными при остановке экземпляра. The elapsed time properties steadily increase while the Stopwatch is running; they remain constant when the instance is stopped.

По умолчанию значение затраченного времени Stopwatch экземпляра равно сумме всех измеренных интервалов времени. By default, the elapsed time value of a Stopwatch instance equals the total of all measured time intervals. Каждый вызов начинает подсчитаться Start на совокупное затраченное время; каждый вызов Stop завершает текущую меру интервала и замораживает совокупное значение затраченного времени. Each call to Start begins counting at the cumulative elapsed time; each call to Stop ends the current interval measurement and freezes the cumulative elapsed time value. Используйте Reset метод для очистки совокупного истекшего времени в существующем Stopwatch экземпляре. Use the Reset method to clear the cumulative elapsed time in an existing Stopwatch instance.

Читайте также:  Линукс сменить язык интерфейса
Оцените статью