Commit 7c501bee authored by Pavel Vainerman's avatar Pavel Vainerman

Оптимизация: перешёл на deque вместо list, там где во основном, проход по списку…

Оптимизация: перешёл на deque вместо list, там где во основном, проход по списку или обавление в начало или конец очереди (буфер).
parent a1a109e4
......@@ -25,7 +25,7 @@
#define SQLiteInterface_H_
// ---------------------------------------------------------------------------
#include <string>
#include <list>
#include <deque>
#include <vector>
#include <iostream>
#include <sqlite3.h>
......@@ -136,7 +136,7 @@ class SQLiteResult
~SQLiteResult();
typedef std::vector<std::string> COL;
typedef std::list<COL> ROW;
typedef std::deque<COL> ROW;
typedef ROW::iterator iterator;
......
......@@ -258,7 +258,7 @@ void IOControl::execute()
waitSM(); // необходимо дождаться, чтобы нормально инициализировать итераторы
PassiveTimer pt(UniSetTimer::WaitUpTime);
if( shm->isLocalwork() )
{
maxItem = 0;
......@@ -276,11 +276,11 @@ void IOControl::execute()
readconf_ok = true; // т.к. waitSM() уже был...
}
maxHalf = maxItem / 2;
dinfo << myname << "(init): iomap size = " << iomap.size() << endl;
cerr << myname << "(iomap size): " << iomap.size() << endl;
//cerr << myname << "(iomap size): " << iomap.size() << endl;
// чтение параметров по входам-выходам
initIOCard();
......@@ -387,10 +387,10 @@ void IOControl::execute()
if( term )
break;
msleep( polltime );
}
term = false;
}
// --------------------------------------------------------------------------------
......@@ -398,7 +398,7 @@ void IOControl::iopoll()
{
if( testmode == tmOffPoll )
return;
// Опрос приоритетной очереди
for( PIOMap::iterator it=pmap.begin(); it!=pmap.end(); ++it )
{
......@@ -419,7 +419,7 @@ void IOControl::iopoll()
IOBase::processingThreshold((IOBase*)&(*it),shm,force);
ioread( (IOInfo*)&(*it) );
// на середине
// опять опросим приоритетные
if( !prior && i>maxHalf )
......@@ -432,11 +432,11 @@ void IOControl::iopoll()
IOBase::processingThreshold((IOBase*)&(iomap[it->index]),shm,force);
}
}
prior = true;
}
}
// Опрос приоритетной очереди
for( PIOMap::iterator it=pmap.begin(); it!=pmap.end(); ++it )
{
......@@ -543,7 +543,7 @@ void IOControl::ioread( IOInfo* it )
card->setDigitalChannel(it->subdev,it->channel,0);
}
break;
case lmpON:
{
if( force_out && (prev_val == lmpBLINK
......@@ -760,7 +760,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
// после инициализации делается resize
// под реальное количество
if( maxItem >= iomap.size() )
iomap.resize(maxItem+10);
iomap.resize(maxItem+90);
int prior = it.getIntProp("iopriority");
if( prior > 0 )
......@@ -771,7 +771,7 @@ bool IOControl::initIOItem( UniXML_iterator& it )
<< it.getProp("name")
<< " priority=" << prior << endl;
}
iomap[maxItem++] = inf;
return true;
}
......@@ -972,9 +972,9 @@ void IOControl::check_testmode()
if( prev_testmode == testmode )
return;
prev_testmode = testmode;
// если режим "выключено всё"
// то гасим все выходы
if( testmode == tmOffPoll )
......@@ -1039,10 +1039,10 @@ void IOControl::check_testlamp()
{
if( force_out )
isTestLamp = shm->localGetValue( itTestLamp, testLamp_S );
if( !trTestLamp.change(isTestLamp) )
return; // если состояние не менялось, то продолжаем работу...
if( isTestLamp )
blink_state = true; // первый такт всегда зажигаем...
......@@ -1054,7 +1054,7 @@ void IOControl::check_testlamp()
{
if( !it->lamp || it->no_testlamp )
continue;
if( it->stype == UniversalIO::AO )
{
if( isTestLamp )
......
......@@ -3,7 +3,7 @@
#define IOControl_H_
// -----------------------------------------------------------------------------
#include <vector>
#include <list>
#include <deque>
#include <string>
#include "UniXML.h"
#include "PassiveTimer.h"
......@@ -316,7 +316,7 @@ class IOControl:
typedef std::vector<IOInfo> IOMap;
IOMap iomap; /*!< список входов/выходов */
typedef std::list<IOPriority> PIOMap;
typedef std::deque<IOPriority> PIOMap;
PIOMap pmap; /*!< список приоритетных входов/выходов */
unsigned int maxItem; /*!< количество элементов (используется на момент инициализации) */
......
......@@ -555,7 +555,7 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
for( ; it.getCurrent(); it.goNext() )
{
HistoryInfo hi;
hi.id = it.getIntProp("id");
hi.id = it.getIntProp("id");
hi.size = it.getIntProp("size");
if( hi.size <= 0 )
continue;
......@@ -589,7 +589,6 @@ void SharedMemory::buildHistoryList( xmlNode* cnode )
<< " fuse_invert=" << hi.fuse_invert
<< endl;
// WARNING: no check duplicates...
hist.push_back(hi);
}
......@@ -609,6 +608,7 @@ void SharedMemory::checkHistoryFilter( UniXML_iterator& xit )
if( !xit.getProp("id").empty() )
{
ai.id = xit.getIntProp("id");
ai.init( it->size, xit.getIntProp("default") );
it->hlst.push_back(ai);
continue;
}
......@@ -620,6 +620,7 @@ void SharedMemory::checkHistoryFilter( UniXML_iterator& xit )
continue;
}
ai.init( it->size, xit.getIntProp("default") );
it->hlst.push_back(ai);
}
}
......
......@@ -280,6 +280,12 @@ class SharedMemory:
{
HistoryItem():id(UniSetTypes::DefaultObjectId){}
inline void init( unsigned int size, long val )
{
if( size > 0 )
buf.assign(size,val);
}
UniSetTypes::ObjectId id;
HBuffer buf;
......@@ -287,9 +293,11 @@ class SharedMemory:
void add( long val, size_t size )
{
// т.е. буфер у нас уже заданного размера
// то просто удаляем очередную точку в начале
// и добавляем в конце
buf.pop_front();
buf.push_back(val);
if( buf.size() >= size )
buf.pop_front();
}
};
......@@ -312,10 +320,10 @@ class SharedMemory:
}
long id; // ID
HistoryList hlst; // history list
HistoryList hlst; // history list
int size;
std::string filter; // filter field
UniSetTypes::ObjectId fuse_id; // fuse sesnsor
std::string filter; // filter field
UniSetTypes::ObjectId fuse_id; // fuse sesnsor
bool fuse_invert;
bool fuse_use_val;
long fuse_val;
......
......@@ -153,7 +153,7 @@ sender2(0)
}
bool resp_invert = n_it.getIntProp("unet_respond_invert");
string s_resp_id(n_it.getProp("unet_respond1_id"));
UniSetTypes::ObjectId resp_id = UniSetTypes::DefaultObjectId;
if( !s_resp_id.empty() )
......@@ -236,7 +236,7 @@ sender2(0)
dcrit << myname << "(init): " << err.str() << endl;
throw SystemError(err.str());
}
}
}
dinfo << myname << "(init): (node='" << n << "') add receiver "
<< h2 << ":" << p2 << endl;
......
......@@ -4,6 +4,7 @@
#include <ostream>
#include <string>
#include <queue>
#include <deque>
#include <cc++/socket.h>
#include "UniSetObject_LT.h"
#include "Trigger.h"
......@@ -115,7 +116,6 @@ class UNetExchange:
void initIterators();
void startReceivers();
enum Timer
{
tmStep
......@@ -180,7 +180,7 @@ class UNetExchange:
IOController::IOStateList::iterator itLostPackets;
};
typedef std::list<ReceiverInfo> ReceiverList;
typedef std::deque<ReceiverInfo> ReceiverList;
ReceiverList recvlist;
bool no_sender; /*!< флаг отключения посылки сообщений (создания потока для посылки)*/
......
......@@ -4,6 +4,7 @@
#include <cmath>
#include <string>
#include <vector>
#include <deque>
#include <ostream>
// -----------------------------------------------------------------------------
/*!
......@@ -232,7 +233,7 @@ class Calibration
}
};
typedef std::vector<CacheInfo> ValueCache;
typedef std::deque<CacheInfo> ValueCache;
ValueCache cache;
unsigned long numCacheResort; // количество обращений, при которых происходит перестроение (сортировка) кэша..
unsigned long numCallToCache; // текущий счётчик обращений к кэшу
......
......@@ -4,7 +4,7 @@
#ifndef DigitalFilter_H_
#define DigitalFilter_H_
//--------------------------------------------------------------------------
#include <list>
#include <deque>
#include <vector>
#include <ostream>
#include "PassiveTimer.h"
......@@ -74,7 +74,7 @@ class DigitalFilter
double S; // Среднеквадратичное отклонение
PassiveTimer tmr;
typedef std::list<int> FIFOBuffer;
typedef std::deque<int> FIFOBuffer;
FIFOBuffer buf;
unsigned int maxsize;
......
......@@ -107,10 +107,10 @@ minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftR
pvec(50),
myname(""),
szCache(5),
cache(5),
numCacheResort(5),
numCacheResort(20),
numCallToCache(5)
{
cache.assign(szCache,CacheInfo());
}
// ----------------------------------------------------------------------------
......@@ -120,10 +120,10 @@ minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftR
pvec(50),
myname(name),
szCache(5),
cache(5),
numCacheResort(5),
numCacheResort(20),
numCallToCache(5)
{
cache.assign(szCache,CacheInfo());
build(name,confile,0);
}
......@@ -131,10 +131,10 @@ numCallToCache(5)
Calibration::Calibration( xmlNode* node ):
minRaw(0),maxRaw(0),minVal(0),maxVal(0),rightVal(0),leftVal(0),rightRaw(0),leftRaw(0),pvec(100),
szCache(5),
cache(5),
numCacheResort(5),
numCacheResort(20),
numCallToCache(5)
{
cache.assign(szCache,CacheInfo());
UniXML_iterator it(node);
myname = it.getProp("name");
build("","",node);
......@@ -326,10 +326,9 @@ void Calibration::setCacheSize( unsigned int sz )
// ----------------------------------------------------------------------------
void Calibration::insertToCache( const long raw, const long val )
{
sort(cache.begin(),cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< )
cache.pop_back(); // удаляем последний элемент (как самый неиспользуемый)
cache.push_back( CacheInfo(raw,val) ); // добавляем в конец..
sort(cache.begin(),cache.end()); // пересортируем с учётом вставки
sort(cache.begin(),cache.end()); // пересортируем в порядке уменьшения обращений (см. CacheInfo::operator< )
}
// ----------------------------------------------------------------------------
long Calibration::getRawValue( long cal, bool range )
......
......@@ -27,6 +27,9 @@ DigitalFilter::DigitalFilter( unsigned int bufsize, double T, double lsq,
coeff_prev(iir_coeff_prev),
coeff_new(iir_coeff_new)
{
buf.resize(maxsize);
mvec.reserve(maxsize);
init(val);
}
//--------------------------------------------------------------------------
DigitalFilter::~DigitalFilter()
......@@ -52,13 +55,14 @@ void DigitalFilter::setSettings( unsigned int bufsize, double T, double lsq,
// удаляем лишние (первые) элементы
int sub = buf.size() - maxsize;
for( unsigned int i=0; i<sub; i++ )
buf.erase( buf.begin() );
buf.pop_front();
}
buf.resize(maxsize);
if( w.size() != maxsize || lsq != lsparam )
w.assign(maxsize, 1.0/maxsize);
lsparam = lsq;
lsparam = lsq;
mvec.resize(maxsize);
}
//--------------------------------------------------------------------------
......@@ -156,9 +160,13 @@ void DigitalFilter::add( int newval )
{
// помещаем очередное значение в буфер
// удаляя при этом старое (FIFO)
// т.к. мы изначально создаём буфер нужного размера и заполням (см. init)
// то каждый раз проверять размер не нужно
// if( buf.size() > maxsize )
// buf.pop_front();
buf.pop_front();
buf.push_back(newval);
if( buf.size() > maxsize )
buf.erase( buf.begin() );
}
//--------------------------------------------------------------------------
int DigitalFilter::current1()
......
......@@ -6,6 +6,9 @@
#include "Extensions.h"
#include "Calibration.h"
#include <vector>
#include <deque>
using namespace std;
using namespace UniSetTypes;
using namespace UniSetExtensions;
......@@ -24,6 +27,12 @@ int main( int argc, const char** argv )
cout << "-540 --> " << cal->getValue(-540) << endl;
cout << "-320 --> " << cal->getValue(-320) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
// проверка кэша....
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
// --------------
cout << "-100 --> " << cal->getValue(-100) << endl;
cout << "-200 --> " << cal->getValue(-200) << endl;
cout << "-100 --> " << cal->getValue(-100) << endl;
......
......@@ -40,7 +40,7 @@ class IOController:
public POA_IOController_i
{
public:
IOController(const std::string& name, const std::string& section);
IOController(UniSetTypes::ObjectId id);
~IOController();
......@@ -91,7 +91,7 @@ class IOController:
UniSetTypes::Message::Priority getPriority(const IOController_i::SensorInfo& si,
UniversalIO::IOType type);
virtual IOController_i::ShortIOInfo getChangedTime(const IOController_i::SensorInfo& si);
virtual IOController_i::ShortMapSeq* getSensors();
......
......@@ -24,7 +24,7 @@
#ifndef Object_LT_H_
#define Object_LT_H_
//--------------------------------------------------------------------------
#include <list>
#include <deque>
#include "UniSetTypes.h"
#include "MessageType.h"
#include "PassiveTimer.h"
......@@ -57,7 +57,6 @@ class UniSetObject;
int sleepTime;
UniSetObject_LT lt;
void callback();
}
void callback()
......@@ -177,7 +176,7 @@ class LT_Object
UniSetTypes::TimerId tid;
};
typedef std::list<TimerInfo> TimersList;
typedef std::deque<TimerInfo> TimersList;
private:
TimersList tlst;
......
......@@ -25,11 +25,13 @@
#ifndef UniSetActivator_H_
#define UniSetActivator_H_
// --------------------------------------------------------------------------
#include <deque>
#include <omniORB4/CORBA.h>
#include "UniSetTypes.h"
#include "UniSetObject.h"
#include "UniSetManager.h"
#include "ThreadCreator.h"
//#include "OmniThreadCreator.h"
//----------------------------------------------------------------------------------------
/*! \class UniSetActivator
......@@ -61,7 +63,6 @@ class UniSetActivator:
protected:
/*! Команды доступные при заказе сигналов
* см. askSignal()
*/
......@@ -126,8 +127,8 @@ class UniSetActivator:
UniSetManager* mnr;
};
std::list<OInfo> lstOInfo;
std::list<MInfo> lstMInfo;
std::deque<OInfo> lstOInfo;
std::deque<MInfo> lstMInfo;
void getinfo();
};
......
......@@ -1606,7 +1606,7 @@ IOController_i::CalibrateInfo UInterface::getCalibrateInfo( const IOController_i
// --------------------------------------------------------------------------------------------
IOController_i::SensorInfoSeq_var UInterface::getSensorSeq( UniSetTypes::IDList& lst )
{
if( lst.size() == 0 )
if( lst.empty() )
return IOController_i::SensorInfoSeq_var();
ObjectId sid = lst.getFirst();
......@@ -1761,7 +1761,7 @@ IDSeq_var UInterface::setOutputSeq( const IOController_i::OutSeq& lst, UniSetTyp
UniSetTypes::IDSeq_var UInterface::askSensorsSeq( UniSetTypes::IDList& lst,
UniversalIO::UIOCommand cmd, UniSetTypes::ObjectId backid )
{
if( lst.size() == 0 )
if( lst.empty() )
return UniSetTypes::IDSeq_var();
if( backid==UniSetTypes::DefaultObjectId )
......
......@@ -70,8 +70,8 @@ static UniSetActivator* gActivator=0;
static int SIGNO;
static int MYPID;
static const int TERMINATE_TIMEOUT = 2; // время отведенное на завершение процесса [сек]
volatile sig_atomic_t procterm = 0;
volatile sig_atomic_t doneterm = 0;
ost::AtomicCounter procterm = 0;
ost::AtomicCounter doneterm = 0;
// PassiveTimer termtmr;
// ------------------------------------------------------------------------------------------
......@@ -353,7 +353,7 @@ void UniSetActivator::sig_child(int signo)
// ------------------------------------------------------------------------------------------
void UniSetActivator::set_signals(bool ask)
{
struct sigaction act, oact;
sigemptyset(&act.sa_mask);
sigemptyset(&oact.sa_mask);
......@@ -482,14 +482,9 @@ void UniSetActivator::term( int signo )
// ------------------------------------------------------------------------------------------
void UniSetActivator::waitDestroy()
{
for(;;)
{
if( doneterm || !gActivator )
break;
while( !doneterm && gActivator )
msleep(50);
}
gActivator = 0;
}
// ------------------------------------------------------------------------------------------
......@@ -259,7 +259,7 @@ using namespace UniSetTypes;
continue;
}
item.fname = s;
item.fname = s;
std::list<std::string> t = UniSetTypes::explode_str(s,'@');
if( t.size() == 1 )
{
......
......@@ -22,6 +22,7 @@
*/
// --------------------------------------------------------------------------
#include <sstream>
#include <algorithm>
#include "Exceptions.h"
#include "UniSetObject.h"
#include "LT_Object.h"
......@@ -50,7 +51,7 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
{
{ // lock
uniset_rwmutex_rlock lock(lstMutex);
if( tlst.empty() )
{
sleepTime = UniSetTimer::WaitUpTime;
......@@ -73,14 +74,14 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
{ // lock
uniset_rwmutex_wrlock lock(lstMutex);
sleepTime = UniSetTimer::WaitUpTime;
for( TimersList::iterator li=tlst.begin();li!=tlst.end();++li)
for( TimersList::iterator li=tlst.begin(); li!=tlst.end(); ++li )
{
if( li->tmr.checkTime() )
{
// помещаем себе в очередь сообщение
TransportMessage tm = TimerMessage(li->id, li->priority, obj->getId()).transport_msg();
obj->push(tm);
// Проверка на количество заданных тактов
if( !li->curTick )
{
......@@ -104,19 +105,19 @@ timeout_t LT_Object::checkTimers( UniSetObject* obj )
// ищем минимальное оставшееся время
if( li->curTimeMS < sleepTime || sleepTime == UniSetTimer::WaitUpTime )
sleepTime = li->curTimeMS;
}
}
if( sleepTime < UniSetTimer::MinQuantityTime )
sleepTime=UniSetTimer::MinQuantityTime;
} // unlock
} // unlock
tmLast.reset();
}
catch(Exception& ex)
catch( Exception& ex )
{
ucrit << "(checkTimers): " << ex << endl;
}
return sleepTime;
}
// ------------------------------------------------------------------------------------------
......@@ -161,11 +162,11 @@ timeout_t LT_Object::askTimer( UniSetTypes::TimerId timerid, timeout_t timeMS, c
{
uinfo << "(LT_askTimer): поступил отказ по таймеру id="<< timerid << endl;
{ // lock
uniset_rwmutex_wrlock lock(lstMutex);
tlst.remove_if(Timer_eq(timerid)); // STL - способ
uniset_rwmutex_wrlock lock(lstMutex);
tlst.erase( std::remove_if(tlst.begin(),tlst.end(),Timer_eq(timerid)) );
} // unlock
}
{ // lock
uniset_rwmutex_rlock lock(lstMutex);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment