diff --git a/cpp/book/book.cpp b/cpp/book/book.cpp index 1c249ae70..7220d4662 100644 --- a/cpp/book/book.cpp +++ b/cpp/book/book.cpp @@ -414,12 +414,14 @@ BookHash ConstSymBookNode::hash() { vector SymBookNode::getSymmetries() { vector symmetries; + symmetries.reserve(node->symmetries.size()); for(int symmetry: node->symmetries) symmetries.push_back(SymmetryHelpers::compose(invSymmetryOfNode, symmetry, symmetryOfNode)); return symmetries; } vector ConstSymBookNode::getSymmetries() { vector symmetries; + symmetries.reserve(node->symmetries.size()); for(int symmetry: node->symmetries) symmetries.push_back(SymmetryHelpers::compose(invSymmetryOfNode, symmetry, symmetryOfNode)); return symmetries; @@ -456,6 +458,7 @@ vector SymBookNode::getUniqueMovesInBook() { vector ConstSymBookNode::getUniqueMovesInBook() { assert(node != nullptr); vector ret; + ret.reserve(node->moves.size()); for(std::pair kv: node->moves) { ret.push_back(kv.second.getSymBookMove(symmetryOfNode, node->book->initialBoard.x_size, node->book->initialBoard.y_size)); } @@ -677,7 +680,7 @@ SymBookNode SymBookNode::playAndAddMove(Board& board, BoardHistory& hist, Loc mo else { childIsTransposing = true; } - child->parents.push_back(std::make_pair(node->hash, bestLoc)); + child->parents.emplace_back(node->hash, bestLoc); BookMove newBookMove( bestLoc, @@ -1021,8 +1024,9 @@ void Book::recomputeMultiThreaded(const std::vector& newAndChangedN // Spawn threads std::vector threads; + threads.reserve(numThreads); for(int i = 0; i < numThreads; i++) { - threads.push_back(std::thread([this, &dirtyNodes, &mutexPool, visitedDoneValue, i]() { + threads.emplace_back([this, &dirtyNodes, &mutexPool, visitedDoneValue, i]() { Rand rand; bool allDirty = false; iterateDirtyNodesPostOrder( @@ -1051,8 +1055,9 @@ void Book::recomputeMultiThreaded(const std::vector& newAndChangedN // Acquire locks in sorted order std::vector> locks; + locks.reserve(mutexIndices.size()); for(uint32_t idx : mutexIndices) { - locks.push_back(std::unique_lock(mutexPool.getMutex(idx))); + locks.emplace_back(mutexPool.getMutex(idx)); } // Now safe to recompute @@ -1063,7 +1068,7 @@ void Book::recomputeMultiThreaded(const std::vector& newAndChangedN &rand, visitedDoneValue ); - })); + }); } // Join all threads @@ -1079,7 +1084,7 @@ void Book::recomputeMultiThreaded(const std::vector& newAndChangedN threads.clear(); for(int i = 0; i < numThreads; i++) { - threads.push_back(std::thread([this, &mutexPool, visitedDoneValueForCosts, i]() { + threads.emplace_back([this, &mutexPool, visitedDoneValueForCosts, i]() { Rand rand; iterateEntireBookPreOrder( [this, &mutexPool](BookNode* node) { @@ -1105,8 +1110,9 @@ void Book::recomputeMultiThreaded(const std::vector& newAndChangedN // Acquire locks in sorted order std::vector> locks; + locks.reserve(mutexIndices.size()); for(uint32_t idx : mutexIndices) { - locks.push_back(std::unique_lock(mutexPool.getMutex(idx))); + locks.emplace_back(mutexPool.getMutex(idx)); } // Now safe to recompute costs @@ -1117,7 +1123,7 @@ void Book::recomputeMultiThreaded(const std::vector& newAndChangedN &rand, visitedDoneValueForCosts ); - })); + }); } // Join all threads @@ -1135,8 +1141,9 @@ void Book::recomputeEverythingMultiThreaded(MutexPool& mutexPool, int numThreads // Spawn threads std::vector threads; + threads.reserve(numThreads); for(int i = 0; i < numThreads; i++) { - threads.push_back(std::thread([this, &mutexPool, visitedDoneValue, i]() { + threads.emplace_back([this, &mutexPool, visitedDoneValue, i]() { Rand rand; bool allDirty = true; iterateDirtyNodesPostOrder( @@ -1165,8 +1172,9 @@ void Book::recomputeEverythingMultiThreaded(MutexPool& mutexPool, int numThreads // Acquire locks in sorted order std::vector> locks; + locks.reserve(mutexIndices.size()); for(uint32_t idx : mutexIndices) { - locks.push_back(std::unique_lock(mutexPool.getMutex(idx))); + locks.emplace_back(mutexPool.getMutex(idx)); } // Now safe to recompute @@ -1177,7 +1185,7 @@ void Book::recomputeEverythingMultiThreaded(MutexPool& mutexPool, int numThreads &rand, visitedDoneValue ); - })); + }); } // Join all threads @@ -1193,7 +1201,7 @@ void Book::recomputeEverythingMultiThreaded(MutexPool& mutexPool, int numThreads threads.clear(); for(int i = 0; i < numThreads; i++) { - threads.push_back(std::thread([this, &mutexPool, visitedDoneValueForCosts, i]() { + threads.emplace_back([this, &mutexPool, visitedDoneValueForCosts, i]() { Rand rand; iterateEntireBookPreOrder( [this, &mutexPool](BookNode* node) { @@ -1219,8 +1227,9 @@ void Book::recomputeEverythingMultiThreaded(MutexPool& mutexPool, int numThreads // Acquire locks in sorted order std::vector> locks; + locks.reserve(mutexIndices.size()); for(uint32_t idx : mutexIndices) { - locks.push_back(std::unique_lock(mutexPool.getMutex(idx))); + locks.emplace_back(mutexPool.getMutex(idx)); } // Now safe to recompute costs @@ -1231,7 +1240,7 @@ void Book::recomputeEverythingMultiThreaded(MutexPool& mutexPool, int numThreads &rand, visitedDoneValueForCosts ); - })); + }); } // Join all threads @@ -1286,6 +1295,7 @@ vector Book::getAllLeaves(double minVisits) { std::vector Book::getAllNodes() { vector ret; + ret.reserve(nodes.size()); for(BookNode* node: nodes) { ret.push_back(SymBookNode(node,0)); } @@ -1520,7 +1530,7 @@ void Book::iterateDirtyNodesPostOrder( auto fillChildren = [&nextChildrenToTry,randToShuffle](const BookNode* node, size_t stackDepth) { if(nextChildrenToTry.size() <= stackDepth) { - nextChildrenToTry.push_back(std::vector()); + nextChildrenToTry.emplace_back(); } assert(nextChildrenToTry[stackDepth].size() == 0); for(auto iter = node->moves.rbegin(); iter != node->moves.rend(); ++iter) { @@ -3312,14 +3322,14 @@ Book* Book::loadFromFile(const std::string& fileName, int numThreadsForRecompute size_t nodeIdx = parentData["id"].get(); BookHash parentHash = hashDict[nodeIdx]; Loc loc = Location::ofString(parentData["loc"].get(),book->initialBoard); - node->parents.push_back(std::make_pair(parentHash,loc)); + node->parents.emplace_back(parentHash,loc); } } else { for(json& parentData: nodeData["parents"]) { BookHash parentHash = BookHash::ofString(parentData["hash"].get()); Loc loc = Location::ofString(parentData["loc"].get(),book->initialBoard); - node->parents.push_back(std::make_pair(parentHash,loc)); + node->parents.emplace_back(parentHash,loc); } } } diff --git a/cpp/command/analysis.cpp b/cpp/command/analysis.cpp index 12c5ccd9c..5aeef0bd9 100644 --- a/cpp/command/analysis.cpp +++ b/cpp/command/analysis.cpp @@ -436,7 +436,7 @@ int MainCmds::analysis(const vector& args) { AsyncBot* bot = new AsyncBot(defaultParams, nnEval, humanEval, &logger, searchRandSeed); bot->setCopyOfExternalPatternBonusTable(patternBonusTable); bot->setExternalEvalCache(evalCache); - threads.push_back(std::thread(analysisLoopProtected,bot,threadIdx)); + threads.emplace_back(analysisLoopProtected,bot,threadIdx); bots.push_back(bot); } @@ -792,7 +792,7 @@ int MainCmds::analysis(const vector& args) { reportErrorForId(rbase.id, field, "Could not parse board location: " + s1); return false; } - buf.push_back(Move(loc,pla)); + buf.emplace_back(loc,pla); } return true; }; diff --git a/cpp/command/contribute.cpp b/cpp/command/contribute.cpp index 1cf94fa8c..c13d90317 100644 --- a/cpp/command/contribute.cpp +++ b/cpp/command/contribute.cpp @@ -1011,7 +1011,7 @@ int MainCmds::contribute(const vector& args) { //Just start based on selfplay games, rating games will poke in as needed vector gameThreads; for(int i = 0; i& args) { int numTaskLoopThreads = 4; vector taskLoopThreads; for(int i = 0; i& args) { std::thread newThread(dataWriteLoopProtected); newThread.detach(); vector threads; + threads.reserve(numGameThreads); for(int i = 0; i& args) { if(loc == Board::NULL_LOC || loc == moveLoc) continue; if(policyProbs[pos] > 0.0 && policyProbs[pos] > 1.5 * moveLocPolicy + 0.05f) - extraMoveLocsToExpand.push_back(std::make_pair(loc,policyProbs[pos])); + extraMoveLocsToExpand.emplace_back(loc,policyProbs[pos]); } std::sort( extraMoveLocsToExpand.begin(), @@ -1361,8 +1361,9 @@ int MainCmds::genbook(const vector& args) { for(SymBookNode node: allNodes) positionsToTrace.forcePush(node); vector threads; + threads.reserve(numGameThreads); for(int gameThreadIdx = 0; gameThreadIdx& args) { for(BookHash hash: nodesHashesToUpdate) hashesToUpdate.forcePush(hash); vector threads; + threads.reserve(numGameThreads); for(int gameThreadIdx = 0; gameThreadIdx& args) { }; vector threads; + threads.reserve(numGameThreads); for(int gameThreadIdx = 0; gameThreadIdx& args) { std::vector nodesToExplore; std::vector depthsToExplore; - nodesToExplore.push_back(book->getRoot()); + nodesToExplore.emplace_back(book->getRoot()); depthsToExplore.push_back(0); logger.write("Beginning book sweep"); @@ -2062,8 +2065,9 @@ int MainCmds::booktoposes(const vector& args) { }; vector threads; + threads.reserve(numThreads); for(int threadIdx = 0; threadIdx& args) { { std::vector nodesToExplore; std::set visited; - nodesToExplore.push_back(NodeAndDepthInfo(book->getRoot(), 0, 0.0, 0.0, 0.0)); + nodesToExplore.emplace_back(book->getRoot(), 0, 0.0, 0.0, 0.0); for(size_t i = 0; i& args) { // Combine all groups into a single vector std::vector allGroups; + allGroups.reserve(groupsByThresholdIncreasing.size()); for(auto& pair : groupsByThresholdIncreasing) { allGroups.push_back(pair.second); } @@ -2495,15 +2500,18 @@ int MainCmds::findbookbottlenecks(const vector& args) { jsonEntry["increasing"] = group.increasing; std::vector nodesToChangeList; + nodesToChangeList.reserve(result.nodes.size()); for(const BookHash& h: result.nodes) nodesToChangeList.push_back(h.toString()); jsonEntry["minSetToChange"] = nodesToChangeList; std::vector nodesToChangeBranchCountsList; + nodesToChangeBranchCountsList.reserve(result.nodes.size()); for(const BookHash& h: result.nodes) nodesToChangeBranchCountsList.push_back(book->getByHash(h).numUniqueMovesInBook()); jsonEntry["minSetToChangeBranchCounts"] = nodesToChangeBranchCountsList; std::vector moveHistoryStrings; + moveHistoryStrings.reserve(moveHistory.size()); for(Loc move: moveHistory) moveHistoryStrings.push_back(Location::toString(move, book->initialBoard)); jsonEntry["moveHistory"] = moveHistoryStrings; @@ -2518,6 +2526,7 @@ int MainCmds::findbookbottlenecks(const vector& args) { testAssert(suc2); std::vector moveHistoryToChangeStrings; + moveHistoryToChangeStrings.reserve(moveHistoryToChange.size()); for(Loc move : moveHistoryToChange) moveHistoryToChangeStrings.push_back(Location::toString(move, book->initialBoard)); moveHistoryToChangeStringss.push_back(moveHistoryToChangeStrings); diff --git a/cpp/command/gtp.cpp b/cpp/command/gtp.cpp index 504f60eaa..01013f383 100644 --- a/cpp/command/gtp.cpp +++ b/cpp/command/gtp.cpp @@ -638,7 +638,7 @@ struct GTPEngine { assert(bot->getRootHist().rules == currentRules); bool suc = bot->makeMove(loc,pla,preventEncore); if(suc) - moveHistory.push_back(Move(loc,pla)); + moveHistory.emplace_back(loc,pla); return suc; } @@ -1034,7 +1034,7 @@ struct GTPEngine { if(moveLocToPlay != Board::NULL_LOC && playChosenMove) { bool suc = bot->makeMove(moveLocToPlay,pla,preventEncore); if(suc) - moveHistory.push_back(Move(moveLocToPlay,pla)); + moveHistory.emplace_back(moveLocToPlay,pla); assert(suc); (void)suc; //Avoid warning when asserts are off @@ -2466,15 +2466,15 @@ int MainCmds::gtp(const vector& args) { else if(command == "kata-list-params") { std::vector paramsList; - paramsList.push_back("analysisWideRootNoise"); - paramsList.push_back("analysisIgnorePreRootHistory"); - paramsList.push_back("genmoveAntiMirror"); - paramsList.push_back("antiMirror"); - paramsList.push_back("humanSLProfile"); - paramsList.push_back("allowResignation"); - paramsList.push_back("ponderingEnabled"); - paramsList.push_back("delayMoveScale"); - paramsList.push_back("delayMoveMax"); + paramsList.emplace_back("analysisWideRootNoise"); + paramsList.emplace_back("analysisIgnorePreRootHistory"); + paramsList.emplace_back("genmoveAntiMirror"); + paramsList.emplace_back("antiMirror"); + paramsList.emplace_back("humanSLProfile"); + paramsList.emplace_back("allowResignation"); + paramsList.emplace_back("ponderingEnabled"); + paramsList.emplace_back("delayMoveScale"); + paramsList.emplace_back("delayMoveMax"); nlohmann::json params = engine->getGenmoveParams().changeableParametersToJson(); for(auto& elt : params.items()) { paramsList.push_back(elt.key()); @@ -2970,7 +2970,7 @@ int MainCmds::gtp(const vector& args) { response += "could not parse vertex: '" + pieces[i+1] + "'"; break; } - initialStones.push_back(Move(loc,pla)); + initialStones.emplace_back(loc,pla); } if(!responseIsError) { maybeSaveAvoidPatterns(false); @@ -3188,7 +3188,7 @@ int MainCmds::gtp(const vector& args) { responseIsError = true; response = "Invalid handicap location: " + pieces[i]; } - locs.push_back(Move(loc,P_BLACK)); + locs.emplace_back(loc,P_BLACK); } bool suc = board.setStonesFailIfNoLibs(locs); if(!suc) { diff --git a/cpp/command/match.cpp b/cpp/command/match.cpp index 9d7fbda90..721c3ef20 100644 --- a/cpp/command/match.cpp +++ b/cpp/command/match.cpp @@ -101,8 +101,8 @@ int MainCmds::match(const vector& args) { if(!includeBot[j]) continue; if(i < j && !(contains(secondaryBotIdxs,i) && contains(secondaryBotIdxs,j))) { - matchupsPerRound.push_back(make_pair(i,j)); - matchupsPerRound.push_back(make_pair(j,i)); + matchupsPerRound.emplace_back(i,j); + matchupsPerRound.emplace_back(j,i); } } } @@ -113,11 +113,11 @@ int MainCmds::match(const vector& args) { int p0 = pair.first; int p1 = pair.second; if(cfg.contains("extraPairsAreOneSidedBW") && cfg.getBool("extraPairsAreOneSidedBW")) { - matchupsPerRound.push_back(std::make_pair(p0,p1)); + matchupsPerRound.emplace_back(p0,p1); } else { - matchupsPerRound.push_back(std::make_pair(p0,p1)); - matchupsPerRound.push_back(std::make_pair(p1,p0)); + matchupsPerRound.emplace_back(p0,p1); + matchupsPerRound.emplace_back(p1,p0); } } } @@ -337,8 +337,9 @@ int MainCmds::match(const vector& args) { Rand hashRand; vector threads; + threads.reserve(numGameThreads); for(int i = 0; i& args) { }; vector threads; + threads.reserve(numGameThreads); for(int i = 0; i& args) { vector threads; for(int i = 0; i& args) { posWriter.start(); vector threads; + threads.reserve(numProcessThreads); for(int i = 0; i& args) { Move move = sgfMoves[m]; moves.push_back(move.loc); - policyTargets.push_back(vector()); - policyTargets[policyTargets.size()-1].push_back(PolicyTargetMove(move.loc,1)); + policyTargets.emplace_back(); + policyTargets[policyTargets.size()-1].emplace_back(move.loc,1); // We want policies learned from human moves to be compatible with KataGo using them in a search which may use // stricter computer rules. So if a player passes, we do NOT train on it. And do NOT train on the opponent's response @@ -2064,7 +2064,7 @@ int MainCmds::writetrainingdata(const vector& args) { Loc moveLoc = search->runWholeSearchAndGetMove(nextPla); moves.push_back(moveLoc); - policyTargets.push_back(vector()); + policyTargets.emplace_back(); Play::extractPolicyTarget(policyTargets[policyTargets.size()-1],search,search->rootNode,locsBuf,playSelectionValuesBuf); // KataGo cleanup moves get weighted a tiny bit, so we can preserve the instinct to cleanup diff --git a/cpp/core/config_parser.cpp b/cpp/core/config_parser.cpp index e78388b63..50d0d21dd 100644 --- a/cpp/core/config_parser.cpp +++ b/cpp/core/config_parser.cpp @@ -461,14 +461,14 @@ void ConfigParser::warnUnusedKeys(ostream& out, Logger* logger) const { vector unused = unusedKeys(); vector messages; if(unused.size() > 0) { - messages.push_back("--------------"); + messages.emplace_back("--------------"); messages.push_back("WARNING: Config had unused keys! You may have a typo, an option you specified is being unused from " + fileName); } for(size_t i = 0; i 0) { - messages.push_back("--------------"); + messages.emplace_back("--------------"); } if(logger) { @@ -665,7 +665,7 @@ vector> ConfigParser::getNonNegativeIntDashedPairs(const stri if(p0 < min || p0 > max || p1 < min || p1 > max) throw IOError("Expected key '" + key + "' to have all values range " + Global::intToString(min) + " to " + Global::intToString(max) + " in config file " + fileName); - ret.push_back(std::make_pair(p0,p1)); + ret.emplace_back(p0,p1); } return ret; } diff --git a/cpp/core/mainargs.cpp b/cpp/core/mainargs.cpp index 84a0316e5..146d95fac 100644 --- a/cpp/core/mainargs.cpp +++ b/cpp/core/mainargs.cpp @@ -32,7 +32,7 @@ std::vector MainArgs::getCommandLineArgsUTF8(int argc, const char* std::vector args; args.reserve(argc); for(int i = 0; i threads; + threads.reserve(numThreads); for(int i = 0; i threads; + threads.reserve(numThreads); for(int i = 0; i threads; - threads.push_back(std::thread(f)); - threads.push_back(std::thread(c0)); - threads.push_back(std::thread(c1)); - threads.push_back(std::thread(c2)); - threads.push_back(std::thread(g)); - threads.push_back(std::thread(h)); + threads.emplace_back(f); + threads.emplace_back(c0); + threads.emplace_back(c1); + threads.emplace_back(c2); + threads.emplace_back(g); + threads.emplace_back(h); for(std::thread& thread: threads) { thread.join(); @@ -186,15 +186,15 @@ void ThreadTest::runTests() { ThreadSafeQueue queue; std::vector writers; std::vector readers; - writers.push_back(std::thread(writer,&queue,0.50)); - writers.push_back(std::thread(writer,&queue,0.40)); - writers.push_back(std::thread(writer,&queue,0.30)); - writers.push_back(std::thread(writer,&queue,0.25)); - writers.push_back(std::thread(writer,&queue,0.20)); - writers.push_back(std::thread(writer,&queue,0.15)); - writers.push_back(std::thread(writer,&queue,0.12)); - writers.push_back(std::thread(writer,&queue,0.10)); - readers.push_back(std::thread(reader,&queue,0.30)); + writers.emplace_back(writer,&queue,0.50); + writers.emplace_back(writer,&queue,0.40); + writers.emplace_back(writer,&queue,0.30); + writers.emplace_back(writer,&queue,0.25); + writers.emplace_back(writer,&queue,0.20); + writers.emplace_back(writer,&queue,0.15); + writers.emplace_back(writer,&queue,0.12); + writers.emplace_back(writer,&queue,0.10); + readers.emplace_back(reader,&queue,0.30); for(std::thread& thread: writers) thread.join(); queue.setReadOnly(); @@ -209,16 +209,16 @@ void ThreadTest::runTests() { ThreadSafeQueue queue; std::vector writers; std::vector readers; - writers.push_back(std::thread(writer,&queue,0.50)); - writers.push_back(std::thread(writer,&queue,0.10)); - readers.push_back(std::thread(reader,&queue,0.50)); - readers.push_back(std::thread(reader,&queue,0.45)); - readers.push_back(std::thread(reader,&queue,0.40)); - readers.push_back(std::thread(reader,&queue,0.35)); - readers.push_back(std::thread(reader,&queue,0.30)); - readers.push_back(std::thread(reader,&queue,0.25)); - readers.push_back(std::thread(reader,&queue,0.20)); - readers.push_back(std::thread(reader,&queue,0.15)); + writers.emplace_back(writer,&queue,0.50); + writers.emplace_back(writer,&queue,0.10); + readers.emplace_back(reader,&queue,0.50); + readers.emplace_back(reader,&queue,0.45); + readers.emplace_back(reader,&queue,0.40); + readers.emplace_back(reader,&queue,0.35); + readers.emplace_back(reader,&queue,0.30); + readers.emplace_back(reader,&queue,0.25); + readers.emplace_back(reader,&queue,0.20); + readers.emplace_back(reader,&queue,0.15); for(std::thread& thread: writers) thread.join(); queue.setReadOnly(); diff --git a/cpp/dataio/files.cpp b/cpp/dataio/files.cpp index c68408ccb..a27588468 100644 --- a/cpp/dataio/files.cpp +++ b/cpp/dataio/files.cpp @@ -161,8 +161,9 @@ void FileHelpers::collectPosesFromDirsOrFiles(const std::vector& di void FileHelpers::sortNewestToOldest(std::vector& files) { vector> filesWithTime; + filesWithTime.reserve(files.size()); for(size_t i = 0; i& moves, int xSize, int ySize) const { for(int x = x1; x <= x2; x++) { for(int y = y1; y <= y2; y++) { Loc loc = Location::getLoc(x,y,xSize); - moves.push_back(Move(loc,color)); + moves.emplace_back(loc,color); } } } @@ -229,10 +229,10 @@ void SgfNode::accumMoves(vector& moves, int xSize, int ySize) const { if(move.pla == C_BLACK) { if((move.x == COORD_MAX && move.y == COORD_MAX) || (move.x == 19 && move.y == 19 && (xSize <= 19 || ySize <= 19))) //handle "tt" - moves.push_back(Move(Board::PASS_LOC,move.pla)); + moves.emplace_back(Board::PASS_LOC,move.pla); else { if(move.x >= xSize || move.y >= ySize) propertyFail("Move out of bounds: " + Global::intToString(move.x) + "," + Global::intToString(move.y)); - moves.push_back(Move(Location::getLoc(move.x,move.y,xSize),move.pla)); + moves.emplace_back(Location::getLoc(move.x,move.y,xSize),move.pla); } } if(props != nullptr && contains(*props,"B")) { @@ -240,16 +240,16 @@ void SgfNode::accumMoves(vector& moves, int xSize, int ySize) const { size_t len = b.size(); for(size_t i = 0; i= xSize || move.y >= ySize) propertyFail("Move out of bounds: " + Global::intToString(move.x) + "," + Global::intToString(move.y)); - moves.push_back(Move(Location::getLoc(move.x,move.y,xSize),move.pla)); + moves.emplace_back(Location::getLoc(move.x,move.y,xSize),move.pla); } } if(props != nullptr && contains(*props,"W")) { @@ -257,7 +257,7 @@ void SgfNode::accumMoves(vector& moves, int xSize, int ySize) const { size_t len = w.size(); for(size_t i = 0; i copy = std::make_unique(board); std::unique_ptr histCopy = std::make_unique(hist); - variationTraceNodesBranch.push_back(std::make_pair((int64_t)nodes.size(),(int64_t)i)); + variationTraceNodesBranch.emplace_back((int64_t)nodes.size(),(int64_t)i); children[i]->iterAllPositionsHelper( *copy,*histCopy,nextPla,rules,xSize,ySize,sampleBuf,uniqueHashes,requireUnique,hashComments,hashParent,flipIfPassOrWFirst,allowGameOver,false,rand,variationTraceNodesBranch,f ); @@ -1095,8 +1095,10 @@ string Sgf::PositionSample::toJsonLine(const Sgf::PositionSample& sample) { data["nextPla"] = PlayerIO::playerToStringShort(sample.nextPla); vector moveLocs; vector movePlas; + moveLocs.reserve(sample.moves.size()); for(size_t i = 0; i(); string hintLocStr = Global::toLower(Global::trim(data["hintLoc"].get())); diff --git a/cpp/game/boardhistory.cpp b/cpp/game/boardhistory.cpp index 5b3c35a9b..28ab81de2 100644 --- a/cpp/game/boardhistory.cpp +++ b/cpp/game/boardhistory.cpp @@ -1012,7 +1012,7 @@ void BoardHistory::makeBoardMoveAssumeLegal(Board& board, Loc moveLoc, Player mo //Update ko recapture blocks and record that this was a ko capture if(board.ko_loc != Board::NULL_LOC) { setKoRecapBlocked(moveLoc,true); - koCapturesInEncore.push_back(EncoreKoCapture(posHashBeforeMove,moveLoc,movePla)); + koCapturesInEncore.emplace_back(posHashBeforeMove,moveLoc,movePla); //Clear simple ko loc now that we've absorbed the ko loc information into the korecap blocks //Once we have that, the simple ko loc plays no further role in game state or legality board.clearSimpleKoLoc(); @@ -1034,7 +1034,7 @@ void BoardHistory::makeBoardMoveAssumeLegal(Board& board, Loc moveLoc, Player mo Hash128 koHashAfterThisMove = getKoHash(rules,board,getOpp(movePla),encorePhase,koRecapBlockHash); koHashHistory.push_back(koHashAfterThisMove); - moveHistory.push_back(Move(moveLoc,movePla)); + moveHistory.emplace_back(moveLoc,movePla); preventEncoreHistory.push_back(preventEncore); numTurnsThisPhase += 1; numApproxValidTurnsThisPhase += 1; diff --git a/cpp/neuralnet/cudabackend.cpp b/cpp/neuralnet/cudabackend.cpp index c76a3dab9..92aebc16b 100644 --- a/cpp/neuralnet/cudabackend.cpp +++ b/cpp/neuralnet/cudabackend.cpp @@ -1158,7 +1158,7 @@ BlockStack::BlockStack( useNHWC ) ); - blocks.push_back(make_pair(ORDINARY_BLOCK_KIND,std::move(blockPtr))); + blocks.emplace_back(ORDINARY_BLOCK_KIND,std::move(blockPtr)); } else if(descBlocks[i].first == GLOBAL_POOLING_BLOCK_KIND) { GlobalPoolingResidualBlockDesc* blockDesc = (GlobalPoolingResidualBlockDesc*)descBlocks[i].second.get(); @@ -1173,7 +1173,7 @@ BlockStack::BlockStack( useNHWC ) ); - blocks.push_back(make_pair(GLOBAL_POOLING_BLOCK_KIND,std::move(blockPtr))); + blocks.emplace_back(GLOBAL_POOLING_BLOCK_KIND,std::move(blockPtr)); } else if(descBlocks[i].first == NESTED_BOTTLENECK_BLOCK_KIND) { NestedBottleneckResidualBlockDesc* blockDesc = (NestedBottleneckResidualBlockDesc*)descBlocks[i].second.get(); @@ -1188,7 +1188,7 @@ BlockStack::BlockStack( useNHWC ) ); - blocks.push_back(make_pair(NESTED_BOTTLENECK_BLOCK_KIND,std::move(blockPtr))); + blocks.emplace_back(NESTED_BOTTLENECK_BLOCK_KIND,std::move(blockPtr)); } else { ASSERT_UNREACHABLE; diff --git a/cpp/neuralnet/desc.cpp b/cpp/neuralnet/desc.cpp index 5ae003cec..121b8ae98 100644 --- a/cpp/neuralnet/desc.cpp +++ b/cpp/neuralnet/desc.cpp @@ -878,7 +878,7 @@ static void parseResidualBlockStack( desc.finalConv.outChannels, trunkNumChannels)); - blocks.push_back(make_pair(ORDINARY_BLOCK_KIND, std::move(descPtr))); + blocks.emplace_back(ORDINARY_BLOCK_KIND, std::move(descPtr)); } else if(kind == "gpool_block") { unique_ptr_void descPtr = make_unique_void(new GlobalPoolingResidualBlockDesc(in, modelVersion, binaryFloats)); @@ -899,7 +899,7 @@ static void parseResidualBlockStack( desc.finalConv.outChannels, trunkNumChannels)); - blocks.push_back(make_pair(GLOBAL_POOLING_BLOCK_KIND, std::move(descPtr))); + blocks.emplace_back(GLOBAL_POOLING_BLOCK_KIND, std::move(descPtr)); } else if(kind == "nested_bottleneck_block") { unique_ptr_void descPtr = make_unique_void(new NestedBottleneckResidualBlockDesc(in,modelVersion,binaryFloats)); @@ -920,7 +920,7 @@ static void parseResidualBlockStack( desc.postConv.outChannels, trunkNumChannels)); - blocks.push_back(make_pair(NESTED_BOTTLENECK_BLOCK_KIND, std::move(descPtr))); + blocks.emplace_back(NESTED_BOTTLENECK_BLOCK_KIND, std::move(descPtr)); } else throw StringError(name + ": found unknown block kind: " + kind); diff --git a/cpp/neuralnet/eigenbackend.cpp b/cpp/neuralnet/eigenbackend.cpp index 9b5d714c3..4ea6d25a5 100644 --- a/cpp/neuralnet/eigenbackend.cpp +++ b/cpp/neuralnet/eigenbackend.cpp @@ -1128,17 +1128,17 @@ BlockStack::BlockStack( if (descBlocks[i].first == ORDINARY_BLOCK_KIND) { ResidualBlockDesc* blockDesc = (ResidualBlockDesc*)descBlocks[i].second.get(); std::unique_ptr block = std::make_unique(*blockDesc,nnX,nnY); - blocks.push_back(make_pair(ORDINARY_BLOCK_KIND, std::move(block))); + blocks.emplace_back(ORDINARY_BLOCK_KIND, std::move(block)); } else if (descBlocks[i].first == GLOBAL_POOLING_BLOCK_KIND) { GlobalPoolingResidualBlockDesc* blockDesc = (GlobalPoolingResidualBlockDesc*)descBlocks[i].second.get(); std::unique_ptr block = std::make_unique(*blockDesc,nnX,nnY); - blocks.push_back(make_pair(GLOBAL_POOLING_BLOCK_KIND, std::move(block))); + blocks.emplace_back(GLOBAL_POOLING_BLOCK_KIND, std::move(block)); } else if (descBlocks[i].first == NESTED_BOTTLENECK_BLOCK_KIND) { NestedBottleneckResidualBlockDesc* blockDesc = (NestedBottleneckResidualBlockDesc*)descBlocks[i].second.get(); std::unique_ptr block = std::make_unique(*blockDesc,nnX,nnY); - blocks.push_back(make_pair(NESTED_BOTTLENECK_BLOCK_KIND, std::move(block))); + blocks.emplace_back(NESTED_BOTTLENECK_BLOCK_KIND, std::move(block)); } else { ASSERT_UNREACHABLE; diff --git a/cpp/neuralnet/openclbackend.cpp b/cpp/neuralnet/openclbackend.cpp index c4bcf2728..c2c4fc1ca 100644 --- a/cpp/neuralnet/openclbackend.cpp +++ b/cpp/neuralnet/openclbackend.cpp @@ -1901,7 +1901,7 @@ BlockStack::BlockStack( useFP16 ) ); - blocks.push_back(make_pair(ORDINARY_BLOCK_KIND,std::move(blockPtr))); + blocks.emplace_back(ORDINARY_BLOCK_KIND,std::move(blockPtr)); } else if(descBlocks[i].first == GLOBAL_POOLING_BLOCK_KIND) { GlobalPoolingResidualBlockDesc* blockDesc = (GlobalPoolingResidualBlockDesc*)descBlocks[i].second.get(); @@ -1914,7 +1914,7 @@ BlockStack::BlockStack( useFP16 ) ); - blocks.push_back(make_pair(GLOBAL_POOLING_BLOCK_KIND,std::move(blockPtr))); + blocks.emplace_back(GLOBAL_POOLING_BLOCK_KIND,std::move(blockPtr)); } else if(descBlocks[i].first == NESTED_BOTTLENECK_BLOCK_KIND) { NestedBottleneckResidualBlockDesc* blockDesc = (NestedBottleneckResidualBlockDesc*)descBlocks[i].second.get(); @@ -1927,7 +1927,7 @@ BlockStack::BlockStack( useFP16 ) ); - blocks.push_back(make_pair(NESTED_BOTTLENECK_BLOCK_KIND,std::move(blockPtr))); + blocks.emplace_back(NESTED_BOTTLENECK_BLOCK_KIND,std::move(blockPtr)); } else { ASSERT_UNREACHABLE; diff --git a/cpp/neuralnet/trtbackend.cpp b/cpp/neuralnet/trtbackend.cpp index c6df9f251..43fac94aa 100644 --- a/cpp/neuralnet/trtbackend.cpp +++ b/cpp/neuralnet/trtbackend.cpp @@ -228,7 +228,7 @@ struct ModelParser { debugOutput->setName(debugOutputName.c_str()); debugOutput->setType(DataType::kFLOAT); debugOutput->setAllowedFormats(1U << static_cast(TensorFormat::kLINEAR)); - model->debugOutputs.push_back(pair(debugOutputName, description)); + model->debugOutputs.emplace_back(debugOutputName, description); #else (void)tensor; (void)description; @@ -1049,7 +1049,7 @@ struct TRTErrorRecorder : IErrorRecorder { } bool reportError(ErrorCode val, IErrorRecorder::ErrorDesc desc) noexcept { std::lock_guard lock(mutex); - errors.push_back(std::make_pair(val,string(desc))); + errors.emplace_back(val,string(desc)); if( (val != ErrorCode::kUNSPECIFIED_ERROR && val != ErrorCode::kSUCCESS) || (errors[errors.size()-1].second.find("Cask convolution") != std::string::npos) diff --git a/cpp/program/play.cpp b/cpp/program/play.cpp index 268a0cbff..031276cb9 100644 --- a/cpp/program/play.cpp +++ b/cpp/program/play.cpp @@ -156,7 +156,7 @@ void GameInitializer::initShared(ConfigParser& cfg, Logger& logger) { int x = allowedBEdges[i]; int y = allowedBEdges[j]; if(x == y) { - allowedBSizes.push_back(std::make_pair(x,y)); + allowedBSizes.emplace_back(x,y); allowedBSizeRelProbs.push_back( (1.0 - allowRectangleProb) * allowedBEdgeRelProbs[i] / relProbSum + allowRectangleProb * allowedBEdgeRelProbs[i] * allowedBEdgeRelProbs[j] / relProbSum / relProbSum @@ -164,7 +164,7 @@ void GameInitializer::initShared(ConfigParser& cfg, Logger& logger) { } else { if(allowRectangleProb > 0.0) { - allowedBSizes.push_back(std::make_pair(x,y)); + allowedBSizes.emplace_back(x,y); allowedBSizeRelProbs.push_back( allowRectangleProb * allowedBEdgeRelProbs[i] * allowedBEdgeRelProbs[j] / relProbSum / relProbSum ); @@ -834,7 +834,7 @@ void Play::extractPolicyTarget( for(int moveIdx = 0; moveIdxsetNNEval(newNNEval); botSpecB.nnEval = newNNEval; botSpecW.nnEval = newNNEval; - gameData->changedNeuralNets.push_back(new ChangedNeuralNet(newNNEval->getModelName(),nextTurnIdx)); + gameData->changedNeuralNets.emplace_back(new ChangedNeuralNet(newNNEval->getModelName(),nextTurnIdx)); } } }; @@ -1573,13 +1571,13 @@ FinishedGameData* Play::runGame( if(!recordFullData) { //Go ahead and record this anyways with just the visits, as a bit of a hack so that the sgf output can also write the number of visits. int64_t unreducedNumVisits = toMoveBot->getRootVisits(); - gameData->policyTargetsByTurn.push_back(PolicyTarget(NULL,unreducedNumVisits)); + gameData->policyTargetsByTurn.emplace_back(nullptr,unreducedNumVisits); } else { vector* policyTarget = new vector(); int64_t unreducedNumVisits = toMoveBot->getRootVisits(); Play::extractPolicyTarget(*policyTarget, toMoveBot, toMoveBot->rootNode, locsBuf, playSelectionValuesBuf); - gameData->policyTargetsByTurn.push_back(PolicyTarget(policyTarget,unreducedNumVisits)); + gameData->policyTargetsByTurn.emplace_back(policyTarget,unreducedNumVisits); gameData->nnRawStatsByTurn.push_back(computeNNRawStats(toMoveBot, board, hist, pla)); gameData->targetWeightByTurn.push_back(limits.targetWeight); diff --git a/cpp/program/selfplaymanager.cpp b/cpp/program/selfplaymanager.cpp index 942a95821..5dce79a74 100644 --- a/cpp/program/selfplaymanager.cpp +++ b/cpp/program/selfplaymanager.cpp @@ -183,6 +183,7 @@ size_t SelfplayManager::numModels() const { vector SelfplayManager::modelNames() const { std::lock_guard lock(managerMutex); vector names; + names.reserve(modelDatas.size()); for(size_t i = 0; imodelName); return names; diff --git a/cpp/tests/testboardbasic.cpp b/cpp/tests/testboardbasic.cpp index fa62b94e5..c95350389 100644 --- a/cpp/tests/testboardbasic.cpp +++ b/cpp/tests/testboardbasic.cpp @@ -2238,7 +2238,7 @@ Caps 4420 4335 for(int y = 0; y permutation(maxBatchSize); rand.fillShuffledUIntRange(maxBatchSize, permutation.data()); vector threads; + threads.reserve(maxBatchSize); for(int i = 0; i permutation(maxBatchSize); rand.fillShuffledUIntRange(maxBatchSize, permutation.data()); vector threads; + threads.reserve(maxBatchSize); for(int i = 0; isetupBoardAndHistAssumeLegal(initialRules, board, nextPla, hist, turnIdx); - items.push_back(NNBatchingTestItem(board,hist,nextPla)); + items.emplace_back(board,hist,nextPla); } }; appendSgfPoses(sgf19x19); @@ -289,8 +289,9 @@ void Tests::runNNBatchingTest(const string& modelFile, bool inputsNHWC, bool use std::fill(ownershipResults.begin(), ownershipResults.end(), 0.0); vector testThreads; + testThreads.reserve(numThreads); for(int threadIdx = 0; threadIdxrootHistory.moveHistory.push_back(Move(Board::NULL_LOC,P_BLACK)); + search->rootHistory.moveHistory.emplace_back(Board::NULL_LOC,P_BLACK); search->searchParams.chosenMoveTemperature = 1.0; search->searchParams.chosenMoveTemperatureEarly = 0.0; diff --git a/cpp/tests/tinymodel.cpp b/cpp/tests/tinymodel.cpp index 510953652..f26b97cee 100644 --- a/cpp/tests/tinymodel.cpp +++ b/cpp/tests/tinymodel.cpp @@ -211,8 +211,9 @@ NNEvaluator* TinyModelTest::runTinyModelTest(const string& baseDir, Logger& logg }; vector testThreads; + testThreads.reserve(4); for(int i = 0; i<4; i++) - testThreads.push_back(std::thread(runAFewTests)); + testThreads.emplace_back(runAFewTests); for(int i = 0; i<4; i++) testThreads[i].join(); @@ -371,8 +372,9 @@ NNEvaluator* TinyModelTest::runTinyModelTest(const string& baseDir, Logger& logg }; vector testThreads; + testThreads.reserve(4); for(int i = 0; i<4; i++) - testThreads.push_back(std::thread(runAFewTests)); + testThreads.emplace_back(runAFewTests); for(int i = 0; i<4; i++) testThreads[i].join(); @@ -494,8 +496,9 @@ NNEvaluator* TinyModelTest::runTinyModelTest(const string& baseDir, Logger& logg }; vector testThreads; + testThreads.reserve(4); for(int i = 0; i<4; i++) - testThreads.push_back(std::thread(runAFewTests)); + testThreads.emplace_back(runAFewTests); for(int i = 0; i<4; i++) testThreads[i].join();