Пишу программу на С++ с использованием WinAPI и необходимо замерить время выполнения участка кода. Подскажите пожалуйста какие-нибудь функции для этого.
Спасибо.
Другие языки программирования и технологии
WinAPI
GetTickCount
Более точная QueryPerformanceCounter
Про RDTSC умолчу, тк это сложновато для новичка.
Влад Оныськив, тебе даны 2 функции для подсчёта времени выполнения. RDTSC пока не трогай - сложно для тебя.
А так просто замеряешь время (в переменную) до и вычитаешь из переменной после эту переменную.
На примере QueryPerformanceCounter:
var t1, t2: int64;
begin
QueryPerformanceCounter(t1);
....
QueryPerformanceCounter(t2);
Result := t2 - t1;
end.
Более точная QueryPerformanceCounter
Про RDTSC умолчу, тк это сложновато для новичка.
Влад Оныськив, тебе даны 2 функции для подсчёта времени выполнения. RDTSC пока не трогай - сложно для тебя.
А так просто замеряешь время (в переменную) до и вычитаешь из переменной после эту переменную.
На примере QueryPerformanceCounter:
var t1, t2: int64;
begin
QueryPerformanceCounter(t1);
....
QueryPerformanceCounter(t2);
Result := t2 - t1;
end.
В дополнение к Мыслителю,
для повышения точности (т. к. сами вызовы QueryPerformanceCounter тоже занимают время) можно повторить участок кода пару десятков раз, а Query... вызвать только один раз в начале и один раз в конце, затем разницу во времени поделить на число повторов. Это если замер очень критичный по точности, а код короткий по времени.
для повышения точности (т. к. сами вызовы QueryPerformanceCounter тоже занимают время) можно повторить участок кода пару десятков раз, а Query... вызвать только один раз в начале и один раз в конце, затем разницу во времени поделить на число повторов. Это если замер очень критичный по точности, а код короткий по времени.
Засечь системное время в начале и в конце. Определить, сколько времени прошло. Или, например, в новом потоке запустить функцию, которая через одну миллисекунду будет увеличивать некую переменную на 1. ( _sleep(1); i++; ). Когда программа дойдет до конца, послать функции сигнал "стоп". Но, мне кажется, это может испортить показания.
clock() //ctime
omp_get_wtime() //omp.h - точнее, но таскать за собой omp только ради замера времени имхо не лучшая идея
omp_get_wtime() //omp.h - точнее, но таскать за собой omp только ради замера времени имхо не лучшая идея
Timer timing;
uint64 t_start = timing.StartTiming();
<!-- do stuff -->
uint64 t_end = timing.StopTiming();
double elapsed_time_ms_global = timing.ElapsedTiming(t_start, t_end);
/*
Copyright (C) 2009 Benjamin Vernoux, titanmkd@gmail.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef TIMING_H
#define TIMING_H
#ifdef __cplusplus
extern "C" {
#endif
#include "global_types.h"
class Timer {
public:
Timer(void);
~Timer(void);
int64 StartTiming(void);
int64 StopTiming(void);
double ElapsedTiming(int64 start, int64 stop);
private:
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
int64 m_Freq; // Frequency for QueryPerformanceFrequency
#endif
};
#ifdef __cplusplus
}
#endif
#endif /* TIMING_H */
/*
Copyright (C) 2009 Benjamin Vernoux, titanmkd@gmail.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Timer class for Win32 or Linux
*/
#include <time.h>
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
#include <windows.h> /* For Win32 QueryPerformanceCounter() */
#endif
#include "timer.h"
Timer::Timer(void)
{
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
QueryPerformanceFrequency((LARGE_INTEGER *)&m_Freq);
#endif
}
Timer::~Timer(void)
{
}
int64 Timer::StartTiming(void)
{
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
int64 i;
if(this->m_Freq != 0)
{
QueryPerformanceCounter((LARGE_INTEGER *)&i);
return i;
}else
return clock();
#else
return clock();
#endif
}
int64 Timer::StopTiming(void)
{
return Timer::StartTiming();
}
double Timer::ElapsedTiming(int64 start, int64 stop)
{
// Returns elapsed time in ms
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
if(this->m_Freq != 0)
{
return ((double)(stop-start)/(double)m_Freq)*1000.0;
}else
return ((double)(stop-start)/(double)CLOCKS_PER_SEC)*1000.0;
#else
return ((double)(stop-start)/(double)CLOCKS_PER_SEC)*1000.0;
#endif
}
uint64 t_start = timing.StartTiming();
<!-- do stuff -->
uint64 t_end = timing.StopTiming();
double elapsed_time_ms_global = timing.ElapsedTiming(t_start, t_end);
/*
Copyright (C) 2009 Benjamin Vernoux, titanmkd@gmail.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef TIMING_H
#define TIMING_H
#ifdef __cplusplus
extern "C" {
#endif
#include "global_types.h"
class Timer {
public:
Timer(void);
~Timer(void);
int64 StartTiming(void);
int64 StopTiming(void);
double ElapsedTiming(int64 start, int64 stop);
private:
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
int64 m_Freq; // Frequency for QueryPerformanceFrequency
#endif
};
#ifdef __cplusplus
}
#endif
#endif /* TIMING_H */
/*
Copyright (C) 2009 Benjamin Vernoux, titanmkd@gmail.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* Timer class for Win32 or Linux
*/
#include <time.h>
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
#include <windows.h> /* For Win32 QueryPerformanceCounter() */
#endif
#include "timer.h"
Timer::Timer(void)
{
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
QueryPerformanceFrequency((LARGE_INTEGER *)&m_Freq);
#endif
}
Timer::~Timer(void)
{
}
int64 Timer::StartTiming(void)
{
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
int64 i;
if(this->m_Freq != 0)
{
QueryPerformanceCounter((LARGE_INTEGER *)&i);
return i;
}else
return clock();
#else
return clock();
#endif
}
int64 Timer::StopTiming(void)
{
return Timer::StartTiming();
}
double Timer::ElapsedTiming(int64 start, int64 stop)
{
// Returns elapsed time in ms
#if (defined(WIN32) || defined(__WIN32__) || defined(__WIN32))
if(this->m_Freq != 0)
{
return ((double)(stop-start)/(double)m_Freq)*1000.0;
}else
return ((double)(stop-start)/(double)CLOCKS_PER_SEC)*1000.0;
#else
return ((double)(stop-start)/(double)CLOCKS_PER_SEC)*1000.0;
#endif
}
Станислав Мартынов
Лучшеб вместо куска бесформенного текста скинул линк на оригинал. Сокращать ссылки кошерно через vk.cc, файло грузить на dropmefiles.com Эти ссылки пропускаются.
Похожие вопросы
- Почему в этой программе переменная объявлена дважды? (C++, WinAPI)
- WINAPI и C++ в целом
- Fasm, вызов WinAPI функций
- Пишут ли еще программы на голом winapi и c++? Или сейчас все пишут при помощи библиотека, таких как Qt?
- В чём разница между WinAPI и DirectX?
- WinAPI используют преимущественно в C++?
- Delphi i WinApi
- Как перебрать все каталоги в текущей директории? (на WinAPI)
- какой winapi функцией можно полусить размеры экрана в миллиметрах либо количество пикселей на миллиметр?
- WinApi + мышь. как проверить, нажата ли кнопка мыши?..