void QMailHeartbeatTimer::setInterval(int minimum, int maximum) { Q_ASSERT(minimum <= maximum); Q_D(QMailHeartbeatTimer); d->timer->setMinimumInterval(toSeconds(minimum)); d->timer->setMaximumInterval(toSeconds(maximum)); }
int main() { #ifndef ONLINE_JUDGE std::ifstream fis("AverageSpeed.in"); std::cin.rdbuf(fis.rdbuf()); #endif std::string line; double currentSpeed = 0.0; size_t lastTime = 0; size_t totalTimeTraveled = 0; double distance = 0.0; while (std::getline(std::cin, line)) { std::istringstream iss(line); std::string time; std::string speed; iss >> time >> speed; size_t seconds = toSeconds(time); size_t delta = seconds - lastTime; lastTime = seconds; totalTimeTraveled += delta; distance += static_cast<double>(delta) * currentSpeed; if (!speed.empty()) { currentSpeed = std::stod(speed) / 3600.00; } else { std::cout << toTime(totalTimeTraveled) << ' ' << std::fixed << std::setprecision(2) << distance << " km" << std::endl; } } return 0; }
struct timespec Yardstick::std_dev() { double average = toSeconds(avg()); double sumDev = 0; for(std::list<struct timespec>::iterator i = time_trials.begin(); i != time_trials.end();i++) { sumDev += pow(toSeconds((*i)) - average,2); } sumDev /= time_trials.size()-1; sumDev = sqrt(sumDev); struct timespec stddev; stddev.tv_sec = (int)sumDev; stddev.tv_nsec = (sumDev - stddev.tv_sec) * BILLION; return stddev; }
//----------------------------------------------------------------------- String timeToString(const Time &value) { if (Time() == value) return String(); Microseconds sinceEpoch = zsLib::timeSinceEpoch<Microseconds>(value); Seconds asSeconds = toSeconds(sinceEpoch); if (asSeconds < sinceEpoch) { return durationToString<Microseconds>(sinceEpoch); } return std::to_string(asSeconds.count()); }
void randomizedTest() { const int cycles = 10000; const int valueRange = 1000; const int removeProbability = 40; //Percent TestSet set; srand(time(nullptr)); for(int a = 0; a < cycles; ++a) { if(a % (cycles / 10) == 0) { qDebug() << "cycle" << a; } bool remove = (rand() % 100) < removeProbability; if(remove && set.size()) { set.remove(set.getItem(rand() % set.size())); }else{ int value = (rand() % valueRange) + 1; set.add(value); } set.verify(); } qDebug() << "Performance embedded list: insertion:" << toSeconds(emb_insertion) << "removal:" << toSeconds(emb_removal) << "contains:" << toSeconds(emb_contains) << "iteration:" << toSeconds(emb_iteration); qDebug() << "Performance std::set: insertion:" << toSeconds(std_insertion) << "removal:" << toSeconds(std_removal) << "contains:" << toSeconds(std_contains) << "iteration:" << toSeconds(std_iteration); }
void ModelContainerView::doGraphics() { i_App->renderDevice->clear(); RenderDevice *rd = i_App->renderDevice; rd->setProjectionAndCameraMatrix(i_App->debugCamera); LightingParameters lighting(GameTime(toSeconds(10, 00, AM))); //i_SkyRef->render(rd,lighting); rd->setAmbientLightColor(Color4(Color3::blue())); rd->enableLighting(); GLight light =GLight::directional(i_App->debugController.getPosition() + i_App->debugController.getLookVector()*2,Color3::white()); rd->setLight(0,light); Array<std::string > keys = iTriVarTable.getKeys(); Array<std::string>::ConstIterator i = keys.begin(); while(i != keys.end()) { VAR* var = iTriVarTable.get(*i); Array<int> indexArray = iTriIndexTable.get(*i); rd->beginIndexedPrimitives(); rd->setVertexArray(*var); rd->sendIndices(RenderDevice::LINES, indexArray); rd->endIndexedPrimitives(); ++i; } i_App->renderDevice->disableLighting(); for(int i=0; i<gBoxArray.size(); ++i) { AABox b = gBoxArray[i]; Draw::box(b,rd,Color3::red()); } if(iDrawLine) { Draw::lineSegment(LineSegment::fromTwoPoints(iPos1, iPos2), rd, iColor, 3); if(myfound) { Draw::lineSegment(LineSegment::fromTwoPoints(p1, p2), rd, iColor, 3); Draw::lineSegment(LineSegment::fromTwoPoints(p2, p3), rd, iColor, 3); Draw::lineSegment(LineSegment::fromTwoPoints(p3, p1), rd, iColor, 3); Draw::sphere(Sphere(p4,0.5),rd, iColor); Draw::sphere(Sphere(p5,0.5),rd, Color3::green()); } } }
Seconds DefaultFileRequestImpl::getRetryTimeout() const { Seconds timeout = Seconds::zero(); if (!response) { // If we don't have a response, we should retry immediately. return timeout; } // A value < 0 means that we should not retry. timeout = Seconds(-1); if (response->error) { assert(failedRequests > 0); switch (response->error->reason) { case Response::Error::Reason::Server: { // Retry immediately, unless we have a certain number of attempts already const int graceRetries = 3; if (failedRequests <= graceRetries) { timeout = Seconds(1); } else { timeout = Seconds(1 << std::min(failedRequests - graceRetries, 31)); } } break; case Response::Error::Reason::Connection: { // Exponential backoff timeout = Seconds(1 << std::min(failedRequests - 1, 31)); } break; default: // Do not retry due to error. break; } } // Check to see if this response expires earlier than a potential error retry. if (response->expires > Seconds::zero()) { const Seconds secsToExpire = response->expires - toSeconds(SystemClock::now()); // Only update the timeout if we don't have one yet, and only if the new timeout is shorter // than the previous one. timeout = timeout < Seconds::zero() ? secsToExpire: std::min(timeout, std::max(Seconds::zero(), secsToExpire)); } return timeout; }
void PandaDocument::step() { m_stepQueued = false; if (m_stepCanceled) // The user clicked stop after a step has been queued { m_stepCanceled = false; return; } auto startTime = std::chrono::high_resolution_clock::now(); panda::helper::UpdateLogger::getInstance()->startLog(this); setInStep(true); // Force the value of isInStep, because some objects will propagate dirtyValue during beginStep for(auto& object : m_objectsList->get()) object->setInStep(true); updateDocumentData(); setDirtyValue(this); updateIfDirty(); setInStep(false); for(auto& object : m_objectsList->get()) object->endStep(); panda::helper::UpdateLogger::getInstance()->stopLog(); m_signals->timeChanged.run(); for (auto obj : m_dirtyObjects) m_signals->dirtyObject.run(obj); m_dirtyObjects.clear(); m_signals->modified.run(); if (m_animPlaying) { m_stepQueued = true; // We want another step if (m_useTimer.getValue()) // Restart the timer taking into consideration the time it took to render this frame { auto endTime = std::chrono::high_resolution_clock::now(); auto frameDuration = std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime); double delay = m_timestep.getValue() - frameDuration.count() / 1000.0 - 0.001; // How long do we wait until we start the next step ? TimedFunctions::cancelRun(m_animFunctionIndex); // Remove previous m_animFunctionIndex = TimedFunctions::delayRun(delay, [this]() { // Ask for the delayed execution of step() m_gui.executeByUI([this]() { step(); }); // But we want step() to be run on the GUI thread }); } else m_gui.executeByUI([this]() { step(); }); // Run ASAP on the GUI thread } ++m_iNbFrames; auto now = currentTime(); float elapsedDur = static_cast<float>(toSeconds(now - m_fpsTime)); if(m_animPlaying && elapsedDur > 1.0) { m_currentFPS = m_iNbFrames / elapsedDur; m_fpsTime = now; m_iNbFrames = 0; } }
void QMailHeartbeatTimer::start(int minimum, int maximum) { Q_ASSERT(minimum <= maximum); Q_D(QMailHeartbeatTimer); d->timer->start(toSeconds(minimum), toSeconds(maximum)); }
void QMailHeartbeatTimer::singleShot(int interval, QObject *receiver, const char *member) { QSystemAlignedTimer::singleShot(toSeconds(interval), toSeconds(interval), receiver, member); }
void QMailHeartbeatTimer::singleShot(int minimum, int maximum, QObject *receiver, const char *member) { Q_ASSERT(minimum <= maximum); QSystemAlignedTimer::singleShot(toSeconds(minimum), toSeconds(maximum), receiver, member); }
void ClientConnection::handleCommand(const std::string& line) { if (boost::iequals(line, "RETRIEVE TASKS")) { auto& query = findTasksForLoginQ(); query.execute(_userId); std::unique_ptr<ClientTask> task; while (query.next(task)) { _stream.writeLine(concatln("TASK ", task->_id, " TITLE ", quoteString(task->_title), " SPENT ", toSeconds(task->_timeSpent))); for (const auto& line : task->_description) { _stream.writeLine(concatln(line)); } _stream.writeLine("\n"); } _stream.writeLine("END TASKS\n"); } else if (boost::iequals(line, "LOG UPLOAD")) { auto& lastEntryTimeQ = findLastLogEntryTimeForClientQ(); lastEntryTimeQ.execute(_clientId); boost::optional<Timestamp> lastEntryTime; bool res = lastEntryTimeQ.next(lastEntryTime); assert(res); assert(! lastEntryTimeQ.next(lastEntryTime)); if (lastEntryTime) { _stream.writeLine(concatln("LAST ENTRY AT ", formatTimestamp(*lastEntryTime))); } else { _stream.writeLine("NO ENTRYS\n"); } int taskId; std::set<std::string> employeeIds; bool loop = true; while (loop) { auto line = _stream.readLine(); LogEntry entry; if (parse(line, TimestampToken(entry._timestamp), " ", BareStringToken(entry._userId), " LOGIN")) { entry._type = LogEntryType_LOGIN; } else if (parse(line, TimestampToken(entry._timestamp), " ", BareStringToken(entry._userId), " LOGOUT")) { entry._type = LogEntryType_LOGOUT; } else if (parse(line, TimestampToken(entry._timestamp), " ", BareStringToken(entry._userId), " TASK ", IntToken(taskId), " START")) { entry._type = LogEntryType_TASK_START; entry._taskId = taskId; } else if (parse(line, TimestampToken(entry._timestamp), " ", BareStringToken(entry._userId), " TASK ", IntToken(taskId), " PAUSE")) { entry._type = LogEntryType_TASK_PAUSE; entry._taskId = taskId; } else if (parse(line, TimestampToken(entry._timestamp), " ", BareStringToken(entry._userId), " TASK ", IntToken(taskId), " FINISH")) { entry._type = LogEntryType_TASK_FINISH; entry._taskId = taskId; } else if (boost::iequals(line, "END LOG")) { loop = false; } else { throw ProtocolError("Invalid log entry", line); } if (loop) { employeeIds.insert(entry._userId); insertLogEntry(entry); } } for (const auto& employeeId : employeeIds) { processLogs(employeeId); } emit tasksStatusChanged(); } else { throw ProtocolError("Invalid command", line); } }
/* **************************************************************************** * * toSeconds - */ TEST(commonGlobals, toSeconds) { int secs; long long longsecs; // 3 years secs = toSeconds(3, 'Y', true); EXPECT_EQ(3 * 365 * 24 * 3600, secs); // error secs = toSeconds(3, 'Y', false); EXPECT_EQ(-1, secs); // 3 months secs = toSeconds(3, 'M', true); EXPECT_EQ(3 * 30 * 24 * 3600, secs); // 3 weeks secs = toSeconds(3, 'W', true); EXPECT_EQ(3 * 7 * 24 * 3600, secs); // 3 days secs = toSeconds(3, 'D', true); EXPECT_EQ(3 * 24 * 3600, secs); // 3 hours secs = toSeconds(3, 'H', false); EXPECT_EQ(3 * 3600, secs); // 3 minutes secs = toSeconds(3, 'M', false); EXPECT_EQ(3 * 60, secs); // 3 seconds secs = toSeconds(3, 'S', false); EXPECT_EQ(3, secs); // error secs = toSeconds(3, 'f', false); EXPECT_EQ(-1, secs); longsecs = toSeconds(30, 'Y', true); EXPECT_EQ(946080000, longsecs); longsecs = toSeconds(300, 'Y', true); EXPECT_EQ(9460800000L, longsecs); }
/***************************************************************************** * * parse8601 - * * This is common code for Duration and Throttling (at least) * */ int64_t parse8601(const std::string& s) { if (s == "") { return -1; } char* duration = strdup(s.c_str()); char* toFree = duration; bool dayPart = true; int64_t accumulated = 0; char* start; if (*duration != 'P') { free(toFree); return -1; } ++duration; start = duration; if (*duration == 0) { free(toFree); return -1; } bool digitsPending = false; while (*duration != 0) { if (isdigit(*duration) || (*duration == '.') || (*duration == ',')) { ++duration; digitsPending = true; } else if ((dayPart == true) && ((*duration == 'Y') || (*duration == 'M') || (*duration == 'D') || (*duration == 'W'))) { char what = *duration; *duration = 0; int value = atoi(start); if ((value == 0) && (*start != '0')) { std::string details = std::string("parse error for duration '") + start + "'"; alarmMgr.badInput(clientIp, details); free(toFree); return -1; } accumulated += toSeconds(value, what, dayPart); digitsPending = false; ++duration; start = duration; } else if ((dayPart == true) && (*duration == 'T')) { dayPart = false; ++duration; start = duration; digitsPending = false; } else if ((dayPart == false) && ((*duration == 'H') || (*duration == 'M') || (*duration == 'S'))) { char what = *duration; int value; *duration = 0; if (what == 'S') // We support floats for the seconds, but only to round to an integer { // NOTE: here we use atof and not str2double on purpose float secs = atof(start); value = (int) round(secs); } else { value = atoi(start); } accumulated += toSeconds(value, what, dayPart); digitsPending = false; ++duration; start = duration; } else { free(toFree); return -1; // ParseError } } free(toFree); if (digitsPending == true) { return -1; } return accumulated; }
double seconds() const { return toSeconds(); }
inline double TimeStamp::inSeconds() const { return toSeconds( stamp_ ); }
inline double TimeStamp::ageInSeconds() const { return toSeconds( this->ageInStamps() ); }
double Yardstick::total() { return toSeconds(avg()) * time_trials.size(); }
void testFiltering() { clock_t stdTime = 0; clock_t algoTime = 0; clock_t treeAlgoTime = 0; clock_t treeAlgoVisitorTime = 0; clock_t insertionStdTime = 0; clock_t insertionAlgoTime = 0; clock_t insertionTreeAlgoTime = 0; typedef Utils::StorableSet<TestItem, TestItemConversion, StaticRepository> RepositorySet; const uint cycles = 3000; const uint setSize = 1500; uint totalItems = 0, totalFilteredItems = 0; srand(time(nullptr)); for(uint a = 0; a < cycles; ++a) { KDevelop::ConvenientFreeListSet<TestItem, TestItemHandler> set1; std::set<uint> testSet1; KDevelop::ConvenientFreeListSet<TestItem, TestItemHandler> set2; std::set<uint> testSet2; RepositorySet repSet2; if(a % (cycles / 10) == 0) { qDebug() << "cycle" << a; } //Build the sets extractor_div_with = (rand() % 10) + 1; for(uint a = 0; a < setSize; ++a) { uint value = rand() % 3000; uint divValue = value/extractor_div_with; if(!divValue) continue; // qDebug() << "inserting" << value; std::set<uint>::const_iterator it = testSet1.lower_bound(value); int pos = set1.iterator().lowerBound(TestItem(value)); //This tests the upperBound functionality if (pos != -1) { QVERIFY(it != testSet1.end()); QVERIFY(set1.data()[pos].value == *it); } else { QVERIFY(it == testSet1.end()); } if((rand() % 10) == 0) { set1.insert(TestItem(value)); testSet1.insert(value); } //This is tuned so in the end, about 99% of all declarations are filtered out, like in the symbol table. if((rand() % (extractor_div_with*100)) == 0) { clock_t start = clock(); set2.insert(TestItem(divValue)); insertionStdTime += clock() - start; start = clock(); testSet2.insert(divValue); insertionAlgoTime += clock() - start; start = clock(); repSet2.insert(TestItem(divValue)); insertionTreeAlgoTime += clock() - start; start = clock(); } } std::set<uint> verifySet1; for(KDevelop::ConvenientFreeListSet<TestItem, TestItemHandler>::Iterator it = set1.iterator(); it; ++it) verifySet1.insert(it->value); std::set<uint> verifySet2; for(KDevelop::ConvenientFreeListSet<TestItem, TestItemHandler>::Iterator it = set2.iterator(); it; ++it) verifySet2.insert(it->value); std::set<uint> verifyRepSet2; for(RepositorySet::Iterator it = repSet2.iterator(); it; ++it) verifyRepSet2.insert((*it).value); QCOMPARE(verifySet1, testSet1); QCOMPARE(verifySet2, testSet2); QCOMPARE(verifyRepSet2, testSet2); std::set<uint> algoFiltered; std::set<uint> treeAlgoFiltered; std::set<uint> treeAlgoVisitorFiltered; { //Do the filtering once without actions on the filtered items, just for calculating the time clock_t start = clock(); { KDevelop::ConvenientEmbeddedSetFilterIterator<TestItem, TestItemHandler, TestItem, TestItemHandler, Extractor> filterIterator(set1.iterator(), set2.iterator()); while(filterIterator) ++filterIterator; algoTime += clock() - start; } start = clock(); { KDevelop::ConvenientEmbeddedSetTreeFilterIterator<TestItem, TestItemHandler, TestItem, RepositorySet, Extractor> filterIterator(set1.iterator(), repSet2); while(filterIterator) ++filterIterator; treeAlgoTime += clock() - start; } { start = clock(); NothingDoVisitor v; KDevelop::ConvenientEmbeddedSetTreeFilterVisitor<TestItem, TestItemHandler, TestItem, RepositorySet, Extractor, NothingDoVisitor> visit(v, set1.iterator(), repSet2); treeAlgoVisitorTime += clock() - start; } start = clock(); for(std::set<uint>::const_iterator it = testSet1.begin(); it != testSet1.end(); ++it) { if(testSet2.count((*it) / extractor_div_with) == 1) { } } stdTime += clock() - start; } { KDevelop::ConvenientEmbeddedSetFilterIterator<TestItem, TestItemHandler, TestItem, TestItemHandler, Extractor> filterIterator(set1.iterator(), set2.iterator()); while(filterIterator) { algoFiltered.insert(filterIterator->value); ++filterIterator; } } { KDevelop::ConvenientEmbeddedSetTreeFilterIterator<TestItem, TestItemHandler, TestItem, RepositorySet, Extractor> filterIterator(set1.iterator(), repSet2); while(filterIterator) { treeAlgoFiltered.insert((*filterIterator).value); ++filterIterator; } } { UintSetVisitor v(treeAlgoVisitorFiltered); KDevelop::ConvenientEmbeddedSetTreeFilterVisitor<TestItem, TestItemHandler, TestItem, RepositorySet, Extractor, UintSetVisitor> visit(v, set1.iterator(), repSet2); } totalItems += testSet1.size(); totalFilteredItems += algoFiltered.size(); std::set<uint> stdFiltered; for(std::set<uint>::const_iterator it = testSet1.begin(); it != testSet1.end(); ++it) { if(testSet2.count((*it) / extractor_div_with) == 1) { stdFiltered.insert(*it); } } QCOMPARE(algoFiltered, stdFiltered); QCOMPARE(treeAlgoFiltered, stdFiltered); QCOMPARE(treeAlgoVisitorFiltered, stdFiltered); } qDebug() << "Filtering performance: embedded-list filtering:" << toSeconds(algoTime) << "set-repository filtering:" << toSeconds(treeAlgoTime) << "set-repository visitor filtering:" << toSeconds(treeAlgoVisitorTime) << "std::set filtering:" << toSeconds(stdTime) << "Normal -> Embedded speedup ratio:" << (toSeconds(stdTime) / toSeconds(algoTime)) << "Normal -> Repository speedup ratio:" << (toSeconds(stdTime) / toSeconds(treeAlgoVisitorTime)) << "total processed items:" << totalItems << "total items after filtering:" << totalFilteredItems; qDebug() << "Insertion: embedded-list:" << toSeconds(insertionAlgoTime) << "set-repository:" << toSeconds(insertionTreeAlgoTime) << "std::set:" << toSeconds(insertionStdTime); }
//------------------------------------------------------------------------------ void A10_Game::move_stuff(TimeVal delta) { FNumber sec = toSeconds(delta); FNumber h_accel = sec * player.horiz_acceleration; //cout << "FPS: " << (1/sec) << endl; //this->status_widget->setText("FPS: "+ToString(1/sec)); this->status_widget->setText("player.speed: "+player.getSpeed().print()+"\nsec: "+ToString(sec)); if(not paused and lives>0) { if( this->kernel->inputMgr->getKeyState(KEY_RIGHT) or this->kernel->inputMgr->getKeyState(KEY_d)) { if( player.getSpeed().x < player.horiz_speed) player.getSpeed().x = player.getSpeed().x + h_accel; else player.getSpeed().x = player.horiz_speed; } else if(this->kernel->inputMgr->getKeyState(KEY_LEFT) or this->kernel->inputMgr->getKeyState(KEY_a)) { if( player.getSpeed().x > -player.horiz_speed) player.getSpeed().x = player.getSpeed().x - h_accel; else player.getSpeed().x = -player.horiz_speed; } else { if(abs(player.getSpeed().x) > h_accel*1.5) player.getSpeed().x = player.getSpeed().x - sgn(player.getSpeed().x)*h_accel*(player.touching?1:0.1); /// slower deacceleration in midair else player.getSpeed().x = 0; } if ( this->kernel->inputMgr->getKeyState(KEY_SPACE) or this->kernel->inputMgr->getKeyState(KEY_UP) or this->kernel->inputMgr->getKeyState(KEY_w)) player.jump(sec); this->player.move(sec, this->getMainMap()); if(this->getMainMap().collides(this->player.shape, 2)) { -- this->lives; if(lives > 0) { this->reset_player(); cout << "died. lives: " << this->lives << endl; //this->pause(); this->died_screen->show(); this->died_screen->alpha = A_OPAQUE; this->died_screen->fadeOut(2); } else { cout << "GAME OVER" << endl; this->restart(); this->pause(); this->gameover_screen->show(); } } this->map_widget ->setDeltaCenter(this->getPlayer().shape.center*(-1)); this->mapf_widget->setDeltaCenter(this->getPlayer().shape.center*(-1)); } this->cursor_pos = this->kernel->inputMgr->getPoint("mouse1").point.pos; this->cursor_delta = this->cursor_pos - this->kernel->graphicsMgr->getScreenSize().cast<Vect::T>()/2; //this->cursor_pos - this->player.shape.center - this->map_widget->getDelta(); };