• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ Milliseconds函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中Milliseconds函数的典型用法代码示例。如果您正苦于以下问题:C++ Milliseconds函数的具体用法?C++ Milliseconds怎么用?C++ Milliseconds使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Milliseconds函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: TEST_F

/**
 * Test that client cursors which have been marked as killed but are still pinned *do not* time out.
 */
TEST_F(CursorManagerTest, InactiveKilledCursorsThatAreStillPinnedShouldNotTimeout) {
    CursorManager* cursorManager = useCursorManager();
    auto clock = useClock();

    // Make a cursor from the plan executor, and immediately kill it.
    auto cursorPin = cursorManager->registerCursor(
        _opCtx.get(),
        {makeFakePlanExecutor(), NamespaceString{"test.collection"}, {}, false, BSONObj()});
    const bool collectionGoingAway = false;
    cursorManager->invalidateAll(
        _opCtx.get(), collectionGoingAway, "KilledCursorsShouldTimeoutTest");

    // Advance the clock to simulate time passing.
    clock->advance(Milliseconds(CursorManager::kDefaultCursorTimeoutMinutes));

    // The pin is still in scope, so it should not time out.
    ASSERT_EQ(0UL, cursorManager->timeoutCursors(_opCtx.get(), clock->now()));
}
开发者ID:mpobrien,项目名称:mongo,代码行数:21,代码来源:cursor_manager_test.cpp


示例2: Milliseconds

void FrameHistory::record(const TimePoint& now, float zoom, const Duration& duration) {

    int16_t zoomIndex = std::floor(zoom * 10.0);

    if (firstFrame) {
        changeTimes.fill(now);

        for (int16_t z = 0; z <= zoomIndex; z++) {
            opacities[z] = 255u;
        }
        firstFrame = false;
    }

    if (zoomIndex < previousZoomIndex) {
        for (int16_t z = zoomIndex + 1; z <= previousZoomIndex; z++) {
            changeTimes[z] = now;
            changeOpacities[z] = opacities[z];
        }
    } else {
        for (int16_t z = zoomIndex; z > previousZoomIndex; z--) {
            changeTimes[z] = now;
            changeOpacities[z] = opacities[z];
        }
    }

    for (int16_t z = 0; z <= 255; z++) {
        std::chrono::duration<float> timeDiff = now - changeTimes[z];
        int32_t opacityChange = (duration == Milliseconds(0) ? 1 : (timeDiff / duration)) * 255;
        if (z <= zoomIndex) {
            opacities[z] = util::min(255, changeOpacities[z] + opacityChange);
        } else {
            opacities[z] = util::max(0, changeOpacities[z] - opacityChange);
        }
    }

    changed = true;

    if (zoomIndex != previousZoomIndex) {
        previousZoomIndex = zoomIndex;
        previousTime = now;
    }

    time = now;
}
开发者ID:Budroid,项目名称:mapbox-gl-native,代码行数:44,代码来源:frame_history.cpp


示例3: Milliseconds

namespace mongo {

const WriteConcernOptions DistLockCatalog::kLocalWriteConcern(1,
                                                              WriteConcernOptions::SyncMode::UNSET,
                                                              Milliseconds(0));

const WriteConcernOptions DistLockCatalog::kMajorityWriteConcern(
    WriteConcernOptions::kMajority,
    // Note: Even though we're setting UNSET here, kMajority implies JOURNAL if journaling is
    // supported by this mongod.
    WriteConcernOptions::SyncMode::UNSET,
    WriteConcernOptions::kWriteConcernTimeoutSystem);

DistLockCatalog::DistLockCatalog() = default;

DistLockCatalog::ServerInfo::ServerInfo(Date_t time, OID _electionId)
    : serverTime(std::move(time)), electionId(std::move(_electionId)) {}

}  // namespace mongo
开发者ID:EvgeniyPatlan,项目名称:percona-server-mongodb,代码行数:19,代码来源:dist_lock_catalog.cpp


示例4: lock

void NoopWriter::_writeNoop(OperationContext* opCtx) {
    // Use GlobalLock + lockMMAPV1Flush instead of DBLock to allow return when the lock is not
    // available. It may happen when the primary steps down and a shared global lock is acquired.
    Lock::GlobalLock lock(
        opCtx, MODE_IX, Date_t::now() + Milliseconds(1), Lock::InterruptBehavior::kLeaveUnlocked);
    if (!lock.isLocked()) {
        LOG(1) << "Global lock is not available skipping noopWrite";
        return;
    }
    opCtx->lockState()->lockMMAPV1Flush();

    auto replCoord = ReplicationCoordinator::get(opCtx);
    // Its a proxy for being a primary
    if (!replCoord->canAcceptWritesForDatabase(opCtx, "admin")) {
        LOG(1) << "Not a primary, skipping the noop write";
        return;
    }

    auto lastAppliedOpTime = replCoord->getMyLastAppliedOpTime();

    // _lastKnownOpTime is not protected by lock as its used only by one thread.
    if (lastAppliedOpTime != _lastKnownOpTime) {
        LOG(1) << "Not scheduling a noop write. Last known OpTime: " << _lastKnownOpTime
               << " != last primary OpTime: " << lastAppliedOpTime;
    } else {
        if (writePeriodicNoops.load()) {
            const auto logLevel = getTestCommandsEnabled() ? 0 : 1;
            LOG(logLevel)
                << "Writing noop to oplog as there has been no writes to this replica set in over "
                << _writeInterval;
            writeConflictRetry(
                opCtx, "writeNoop", NamespaceString::kRsOplogNamespace.ns(), [&opCtx] {
                    WriteUnitOfWork uow(opCtx);
                    opCtx->getClient()->getServiceContext()->getOpObserver()->onOpMessage(opCtx,
                                                                                          kMsgObj);
                    uow.commit();
                });
        }
    }

    _lastKnownOpTime = replCoord->getMyLastAppliedOpTime();
    LOG(1) << "Set last known op time to " << _lastKnownOpTime;
}
开发者ID:louiswilliams,项目名称:mongo,代码行数:43,代码来源:noop_writer.cpp


示例5: TEST

TEST(AsyncTimerMock, Cancel) {
    AsyncTimerFactoryMock factory;

    // Set a timer
    bool fired = false;
    auto timer = factory.make(Milliseconds(100));
    timer->asyncWait([&fired](std::error_code ec) {
        // This timer should have been canceled
        ASSERT(ec);
        ASSERT(ec == asio::error::operation_aborted);
        fired = true;
    });

    // Cancel timer
    timer->cancel();

    // Ensure that its handler was called
    ASSERT(fired);
}
开发者ID:DINKIN,项目名称:mongo,代码行数:19,代码来源:async_timer_mock_test.cpp


示例6: ScheduleTasks

            void ScheduleTasks() override
            {
                scheduler.Schedule(Seconds(8), Seconds(10), [this](TaskContext task)
                {
                    DoCastAOE(SPELL_ARCANE_BARRAGE_VOLLEY);
                    task.Repeat(Seconds(8), Seconds(10));
                });

                scheduler.Schedule(Seconds(10), Seconds(11), [this](TaskContext task)
                {
                    if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 45.0f, true))
                        DoCast(target, SPELL_ARCANE_BUFFET);
                    task.Repeat(Seconds(15), Seconds(20));
                });

                scheduler.Schedule(Seconds(5), [this](TaskContext task)
                {
                    Talk(SAY_REPEAT_SUMMON);

                    std::list<uint8> summonSpells = { 0, 1, 2 };

                    uint8 spell = Trinity::Containers::SelectRandomContainerElement(summonSpells);
                    DoCast(me, EtherealSphereSummonSpells[spell]);
                    summonSpells.remove(spell);

                    if (IsHeroic())
                    {
                        spell = Trinity::Containers::SelectRandomContainerElement(summonSpells);
                        task.Schedule(Milliseconds(2500), [this, spell](TaskContext /*task*/)
                        {
                            DoCast(me, EtherealSphereHeroicSummonSpells[spell]);
                        });
                    }

                    task.Schedule(Seconds(33), Seconds(35), [this](TaskContext /*task*/)
                    {
                        DummyEntryCheckPredicate pred;
                        summons.DoAction(ACTION_SUMMON, pred);
                    });

                    task.Repeat(Seconds(45), Seconds(47));
                });
            }
开发者ID:FixCore,项目名称:335source,代码行数:43,代码来源:boss_xevozz.cpp


示例7: invariant

void NetworkInterfaceMock::_enqueueOperation_inlock(
    mongo::executor::NetworkInterfaceMock::NetworkOperation&& op) {
    auto insertBefore =
        std::upper_bound(std::begin(_unscheduled),
                         std::end(_unscheduled),
                         op,
                         [](const NetworkOperation& a, const NetworkOperation& b) {
                             return a.getNextConsiderationDate() < b.getNextConsiderationDate();
                         });

    _unscheduled.emplace(insertBefore, std::move(op));

    if (op.getRequest().timeout != RemoteCommandRequest::kNoTimeout) {
        invariant(op.getRequest().timeout >= Milliseconds(0));
        ResponseStatus response(ErrorCodes::NetworkTimeout, "Network timeout");
        auto action = stdx::bind(
            &NetworkInterfaceMock::_cancelCommand_inlock, this, op.getCallbackHandle(), response);
        _alarms.emplace(_now_inlock() + op.getRequest().timeout, action);
    }
}
开发者ID:EmielZuurbier,项目名称:mongo,代码行数:20,代码来源:network_interface_mock.cpp


示例8: Milliseconds

namespace util {

constexpr float tileSize = 512;

/*
 * The maximum extent of a feature that can be safely stored in the buffer.
 * In practice, all features are converted to this extent before being added.
 *
 * Positions are stored as signed 16bit integers.
 * One bit is lost for signedness to support features extending past the left edge of the tile.
 * One bit is lost because the line vertex buffer packs 1 bit of other data into the int.
 * One bit is lost to support features extending past the extent on the right edge of the tile.
 * This leaves us with 2^13 = 8192
 */
constexpr int32_t EXTENT = 8192;

constexpr double DEG2RAD = M_PI / 180.0;
constexpr double RAD2DEG = 180.0 / M_PI;
constexpr double M2PI = M_PI * 2;
constexpr double EARTH_RADIUS_M = 6378137;
constexpr double LATITUDE_MAX = 85.051128779806604;
constexpr double LONGITUDE_MAX = 180;
constexpr double DEGREES_MAX = 360;
constexpr double PITCH_MAX = M_PI / 3;
constexpr double MIN_ZOOM = 0.0;
constexpr double MAX_ZOOM = 25.5;
constexpr float  MIN_ZOOM_F = MIN_ZOOM;
constexpr float  MAX_ZOOM_F = MAX_ZOOM;

constexpr uint64_t DEFAULT_MAX_CACHE_SIZE = 50 * 1024 * 1024;

constexpr Duration DEFAULT_FADE_DURATION = Milliseconds(300);
constexpr Seconds CLOCK_SKEW_RETRY_TIMEOUT { 30 };

constexpr UnitBezier DEFAULT_TRANSITION_EASE = { 0, 0, 0.25, 1 };
    
constexpr int DEFAULT_RATE_LIMIT_TIMEOUT = 5;

constexpr const char* API_BASE_URL = "https://api.mapbox.com";
    
} // namespace util
开发者ID:akikoskinen,项目名称:mapbox-gl-native,代码行数:41,代码来源:constants.hpp


示例9: TEST_F

TEST_F(TransactionCoordinatorServiceTest,
       CoordinatorIsNotCanceledIfDeadlinePassesButHasReceivedParticipantList) {
    auto coordinatorService = TransactionCoordinatorService::get(operationContext());
    const auto deadline = executor()->now() + Milliseconds(1000 * 60 * 10 /* 10 hours */);
    coordinatorService->createCoordinator(operationContext(), _lsid, _txnNumber, deadline);

    // Deliver the participant list before the deadline.
    ASSERT(boost::none !=
           coordinatorService->coordinateCommit(
               operationContext(), _lsid, _txnNumber, kTwoShardIdSet));

    // Reach the deadline.
    network()->enterNetwork();
    network()->advanceTime(deadline);
    network()->exitNetwork();

    // The coordinator should still exist.
    ASSERT(boost::none !=
           coordinatorService->coordinateCommit(
               operationContext(), _lsid, _txnNumber, kTwoShardIdSet));
}
开发者ID:ajdavis,项目名称:mongo,代码行数:21,代码来源:transaction_coordinator_service_test.cpp


示例10: Reset

    void Reset() override
    {
        me->SetReactState(REACT_PASSIVE);
        me->SetDisplayId(me->GetCreatureTemplate()->Modelid2);
        DoCastSelf(SPELL_PUTRID_MUSHROOM);
        DoCastSelf(SPELL_SHRINK, true);
        DoCastSelf(SPELL_GROW, true);

        if (me->GetEntry() == NPC_HEALTHY_MUSHROOM)
        {
            DoCastSelf(SPELL_POWER_MUSHROOM_VISUAL_AURA);
            _active = true;
        }
        else
            DoCastSelf(SPELL_POISONOUS_MUSHROOM_VISUAL_AURA);

        _scheduler.Schedule(Milliseconds(800), [this](TaskContext /*context*/)
        {
            DoCastSelf(SPELL_GROW, true);
        });
    }
开发者ID:ElunaLuaEngine,项目名称:ElunaTrinityWotlk,代码行数:21,代码来源:boss_amanitar.cpp


示例11: tick

    void tick( Milliseconds current_time_in_milliseconds )
    {
        if ( m_last_flush_time == Milliseconds( 0 ) )
        {
            // initialize last_flush_time
            m_last_flush_time = current_time_in_milliseconds;
        }
        else
        {
            // is it time to check?
            if ( ( current_time_in_milliseconds - m_last_flush_time ) > m_flush_period_in_milliseconds )
            {
                // yes, remember when we did
                m_last_flush_time = current_time_in_milliseconds;

                // flush any expired addresses
                flushKnownAddressesFromMap(
                    m_known_entity_addresses, m_expiry_time_in_milliseconds, current_time_in_milliseconds );
            }
        }
    }
开发者ID:jdkoftinoff,项目名称:ControlPlane,代码行数:21,代码来源:AvdeccDirector.hpp


示例12: _viewMode

AutoGetCollection::AutoGetCollection(OperationContext* opCtx,
                                     const NamespaceString& nss,
                                     LockMode modeDB,
                                     LockMode modeColl,
                                     ViewMode viewMode)
    : _viewMode(viewMode),
      _autoDb(opCtx, nss.db(), modeDB),
      _collLock(opCtx->lockState(), nss.ns(), modeColl),
      _coll(_autoDb.getDb() ? _autoDb.getDb()->getCollection(opCtx, nss) : nullptr) {
    Database* db = _autoDb.getDb();
    // If the database exists, but not the collection, check for views.
    if (_viewMode == ViewMode::kViewsForbidden && db && !_coll &&
        db->getViewCatalog()->lookup(opCtx, nss.ns()))
        uasserted(ErrorCodes::CommandNotSupportedOnView,
                  str::stream() << "Namespace " << nss.ns() << " is a view, not a collection");

    // Wait for a configured amount of time after acquiring locks if the failpoint is enabled.
    MONGO_FAIL_POINT_BLOCK(setAutoGetCollectionWait, customWait) {
        const BSONObj& data = customWait.getData();
        sleepFor(Milliseconds(data["waitForMillis"].numberInt()));
    }
}
开发者ID:mpobrien,项目名称:mongo,代码行数:22,代码来源:db_raii.cpp


示例13: UpdateAI

            void UpdateAI(uint32 diff) override
            {
                if (!UpdateVictim())
                    return;

                events.Update(diff);

                if (me->HasUnitState(UNIT_STATE_CASTING))
                    return;

                while (uint32 eventId = events.ExecuteEvent())
                {
                    switch (eventId)
                    {
                        case EVENT_POISON:
                            if (!me->HasAura(SPELL_WIDOWS_EMBRACE_HELPER))
                                DoCastAOE(SPELL_POISON_BOLT_VOLLEY);
                            events.Repeat(randtime(Seconds(8), Seconds(15)));
                            break;
                        case EVENT_FIRE:
                            if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
                                DoCast(target, SPELL_RAIN_OF_FIRE);
                            events.Repeat(randtime(Seconds(6), Seconds(18)));
                            break;
                        case EVENT_FRENZY:
                            if (Aura* widowsEmbrace = me->GetAura(SPELL_WIDOWS_EMBRACE_HELPER))
                                events.ScheduleEvent(EVENT_FRENZY, Milliseconds(widowsEmbrace->GetDuration()+1));
                            else
                            {
                                DoCast(SPELL_FRENZY);
                                Talk(EMOTE_FRENZY);
                                events.Repeat(Minutes(1) + randtime(Seconds(0), Seconds(20)));
                            }
                            break;
                    }
                }

                DoMeleeAttackIfReady();
            }
开发者ID:DanielBallaSZTE,项目名称:TrinityCorePreWOTLK,代码行数:39,代码来源:boss_faerlina.cpp


示例14: ProcessJoystickEvents

bool WindowImpl::PopEvent(Event& event, bool block)
{
    // If the event queue is empty, let's first check if new events are available from the OS
    if (myEvents.empty())
    {
        if (!block)
        {
            // Non-blocking mode: process events and continue
            ProcessJoystickEvents();
            ProcessEvents();
        }
        else
        {
            // Blocking mode: process events until one is triggered

            // Here we use a manual wait loop instead of the optimized
            // wait-event provided by the OS, so that we don't skip joystick
            // events (which require polling)
            while (myEvents.empty())
            {
                ProcessJoystickEvents();
                ProcessEvents();
                Sleep(Milliseconds(10));
            }
        }
    }

    // Pop the first event of the queue, if it is not empty
    if (!myEvents.empty())
    {
        event = myEvents.front();
        myEvents.pop();

        return true;
    }

    return false;
}
开发者ID:coolhome,项目名称:SFML,代码行数:38,代码来源:WindowImpl.cpp


示例15: lock

Status SyncSourceFeedback::_updateUpstream(OperationContext* txn, BackgroundSync* bgsync) {
    Reporter* reporter;
    {
        stdx::lock_guard<stdx::mutex> lock(_mtx);
        reporter = _reporter;
    }

    auto syncTarget = reporter->getTarget();

    auto triggerStatus = reporter->trigger();
    if (!triggerStatus.isOK()) {
        warning() << "unable to schedule reporter to update replication progress on " << syncTarget
                  << ": " << triggerStatus;
        return triggerStatus;
    }

    auto status = reporter->join();

    if (!status.isOK()) {
        log() << "SyncSourceFeedback error sending update to " << syncTarget << ": " << status;

        // Some errors should not cause result in blacklisting the sync source.
        if (status != ErrorCodes::InvalidSyncSource) {
            // The command could not be created because the node is now primary.
        } else if (status != ErrorCodes::NodeNotFound) {
            // The command could not be created, likely because this node was removed from the set.
        } else {
            // Blacklist sync target for .5 seconds and find a new one.
            stdx::lock_guard<stdx::mutex> lock(_mtx);
            auto replCoord = repl::ReplicationCoordinator::get(txn);
            replCoord->blacklistSyncSource(syncTarget, Date_t::now() + Milliseconds(500));
            bgsync->clearSyncTarget();
        }
    }

    return status;
}
开发者ID:AshishSanju,项目名称:mongo,代码行数:37,代码来源:sync_source_feedback.cpp


示例16: dassert

Status MigrationChunkClonerSourceLegacy::nextCloneBatch(OperationContext* txn,
                                                        Collection* collection,
                                                        BSONArrayBuilder* arrBuilder) {
    dassert(txn->lockState()->isCollectionLockedForMode(_args.getNss().ns(), MODE_IS));

    ElapsedTracker tracker(txn->getServiceContext()->getFastClockSource(),
                           internalQueryExecYieldIterations,
                           Milliseconds(internalQueryExecYieldPeriodMS.load()));

    stdx::lock_guard<stdx::mutex> sl(_mutex);

    std::set<RecordId>::iterator it;

    for (it = _cloneLocs.begin(); it != _cloneLocs.end(); ++it) {
        // We must always make progress in this method by at least one document because empty return
        // indicates there is no more initial clone data.
        if (arrBuilder->arrSize() && tracker.intervalHasElapsed()) {
            break;
        }

        Snapshotted<BSONObj> doc;
        if (collection->findDoc(txn, *it, &doc)) {
            // Use the builder size instead of accumulating the document sizes directly so that we
            // take into consideration the overhead of BSONArray indices.
            if (arrBuilder->arrSize() &&
                (arrBuilder->len() + doc.value().objsize() + 1024) > BSONObjMaxUserSize) {
                break;
            }

            arrBuilder->append(doc.value());
        }
    }

    _cloneLocs.erase(_cloneLocs.begin(), it);

    return Status::OK();
}
开发者ID:ChineseDr,项目名称:mongo,代码行数:37,代码来源:migration_chunk_cloner_source_legacy.cpp


示例17: func

void NetworkTestEnv::onCommandWithMetadata(OnCommandWithMetadataFunction func) {
    _mockNetwork->enterNetwork();

    const NetworkInterfaceMock::NetworkOperationIterator noi = _mockNetwork->getNextReadyRequest();
    const RemoteCommandRequest& request = noi->getRequest();

    const auto cmdResponseStatus = func(request);

    BSONObjBuilder result;

    if (cmdResponseStatus.isOK()) {
        result.appendElements(cmdResponseStatus.data);
        Command::appendCommandStatus(result, cmdResponseStatus.status);
        const RemoteCommandResponse response(
            result.obj(), cmdResponseStatus.metadata, Milliseconds(1));

        _mockNetwork->scheduleResponse(noi, _mockNetwork->now(), response);
    } else {
        _mockNetwork->scheduleResponse(noi, _mockNetwork->now(), cmdResponseStatus.status);
    }

    _mockNetwork->runReadyNetworkOperations();
    _mockNetwork->exitNetwork();
}
开发者ID:ChineseDr,项目名称:mongo,代码行数:24,代码来源:network_test_env.cpp


示例18: TEST_F


//.........这里部分代码省略.........
  EXPECT_NE(0u, offers.get().size());

  TaskInfo task;
  task.set_name("isolator_test");
  task.mutable_task_id()->set_value("1");
  task.mutable_slave_id()->CopyFrom(offers.get()[0].slave_id());
  task.mutable_resources()->CopyFrom(offers.get()[0].resources());

  Resources resources(offers.get()[0].resources());
  Option<Bytes> mem = resources.mem();
  ASSERT_SOME(mem);
  Option<double> cpus = resources.cpus();
  ASSERT_SOME(cpus);

  const std::string& file = path::join(flags.work_dir, "ready");

  // This task induces user/system load in a child process by
  // running top in a child process for ten seconds.
  task.mutable_command()->set_value(
#ifdef __APPLE__
      // Use logging mode with 30,000 samples with no interval.
      "top -l 30000 -s 0 2>&1 > /dev/null & "
#else
      // Batch mode, with 30,000 samples with no interval.
      "top -b -d 0 -n 30000 2>&1 > /dev/null & "
#endif
      "touch " + file +  "; " // Signals that the top command is running.
      "sleep 60");

  Future<TaskStatus> status;
  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status))
    .WillRepeatedly(Return()); // Ignore rest for now.

  Future<ContainerID> containerId;
  EXPECT_CALL(containerizer, launch(_, _, _, _, _, _, _, _))
    .WillOnce(DoAll(FutureArg<0>(&containerId),
                    Invoke(&containerizer,
                           &MockExternalContainerizer::_launch)));

  driver.launchTasks(offers.get()[0].id(), {task});

  AWAIT_READY(containerId);

  AWAIT_READY(status);

  EXPECT_EQ(TASK_RUNNING, status.get().state());

  // Wait for the task to begin inducing cpu time.
  while (!os::exists(file));

  ExecutorID executorId;
  executorId.set_value(task.task_id().value());

  // We'll wait up to 10 seconds for the child process to induce
  // 1/8 of a second of user and system cpu time in total.
  // TODO(bmahler): Also induce rss memory consumption, by re-using
  // the balloon framework.
  ResourceStatistics statistics;
  Duration waited = Duration::zero();
  do {
    Future<ResourceStatistics> usage = containerizer.usage(containerId.get());
    AWAIT_READY(usage);

    statistics = usage.get();

    // If we meet our usage expectations, we're done!
    // NOTE: We are currently getting dummy-data from the test-
    // containerizer python script matching these expectations.
    // TODO(tillt): Consider working with real data.
    if (statistics.cpus_user_time_secs() >= 0.120 &&
        statistics.cpus_system_time_secs() >= 0.05 &&
        statistics.mem_rss_bytes() >= 1024u) {
      break;
    }

    os::sleep(Milliseconds(100));
    waited += Milliseconds(100);
  } while (waited < Seconds(10));

  EXPECT_GE(statistics.cpus_user_time_secs(), 0.120);
  EXPECT_GE(statistics.cpus_system_time_secs(), 0.05);
  EXPECT_EQ(statistics.cpus_limit(), cpus.get());
  EXPECT_GE(statistics.mem_rss_bytes(), 1024u);
  EXPECT_EQ(statistics.mem_limit_bytes(), mem.get().bytes());

  EXPECT_CALL(sched, statusUpdate(&driver, _))
    .WillOnce(FutureArg<1>(&status));

  driver.killTask(task.task_id());

  AWAIT_READY(status);

  EXPECT_EQ(TASK_KILLED, status.get().state());

  driver.stop();
  driver.join();

  this->Shutdown();
}
开发者ID:lins05,项目名称:mesos,代码行数:101,代码来源:external_containerizer_test.cpp


示例19: script_name


//.........这里部分代码省略.........
  if (print_run_time()) {
    *stream() <<
    "      <tr>\n"
    "        <td>Duration</td>\n"
    "        <td>" << TimeSpan(stats->GetTotalRunTime()) << "</td>\n"
    "      </tr>\n"
    ;
  }

  *stream() <<
  "    </tbody>\n"
  "  </table>\n"
  "  <br/>\n"
  "  <table id=\"data\" class=\"tablesorter\">\n"
  "    <thead>\n"
  "      <tr>\n"
  "        <th rowspan=\"2\">Type</th>\n"
  "        <th rowspan=\"2\">Name</th>\n"
  "        <th rowspan=\"2\">Calls</th>\n"
  "        <th colspan=\"4\" class=\"group\">Self Time</th>\n"
  "        <th colspan=\"4\" class=\"group\">Total Time</th>\n"
  "      </tr>\n"
  "      <tr>\n"
  "        <th>%</th>\n"
  "        <th>Overall</th>\n"
  "        <th>Average</th>\n"
  "        <th>Worst</th>\n"
  "        <th>%</th>\n"
  "        <th>Overall</th>\n"
  "        <th>Average</th>\n"
  "        <th>Worst</th>\n"
  "      </tr>\n"
  "    </thead>\n"
  "    <tbody>\n"
  ;

  std::vector<FunctionStatistics*> all_fn_stats;
  stats->GetStatistics(all_fn_stats);

  Nanoseconds self_time_all;
  for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
       iterator != all_fn_stats.end(); ++iterator)
  {
    const FunctionStatistics *fn_stats = *iterator;
    self_time_all += fn_stats->self_time();
  };

  Nanoseconds total_time_all;
  for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
       iterator != all_fn_stats.end(); ++iterator)
  {
    const FunctionStatistics *fn_stats = *iterator;
    total_time_all += fn_stats->total_time();
  };

  std::ostream::fmtflags flags = stream()->flags();
  stream()->flags(flags | std::ostream::fixed);

  for (std::vector<FunctionStatistics*>::const_iterator iterator = all_fn_stats.begin();
       iterator != all_fn_stats.end(); ++iterator)
  {
    const FunctionStatistics *fn_stats = *iterator;

    double self_time_percent = fn_stats->self_time().count() * 100 / self_time_all.count();
    double total_time_percent = fn_stats->total_time().count() * 100 / total_time_all.count();

    double self_time = Seconds(fn_stats->self_time()).count();
    double total_time = Seconds(fn_stats->total_time()).count();

    double avg_self_time = Milliseconds(fn_stats->self_time()).count() / fn_stats->num_calls();
    double avg_total_time = Milliseconds(fn_stats->total_time()).count() / fn_stats->num_calls();

    double worst_self_time = Milliseconds(fn_stats->worst_self_time()).count();
    double worst_total_time = Milliseconds(fn_stats->worst_total_time()).count();

    *stream()
    << "    <tr>\n"
    << "      <td>" << fn_stats->function()->GetTypeString() << "</td>\n"
    << "      <td>" << fn_stats->function()->name() << "</td>\n"
    << "      <td>" << fn_stats->num_calls() << "</td>\n"
    << "      <td>" << std::setprecision(2) << self_time_percent << "%</td>\n"
    << "      <td>" << std::setprecision(1) << self_time << "</td>\n"
    << "      <td>" << std::setprecision(1) << avg_self_time << "</td>\n"
    << "      <td>" << std::setprecision(1) << worst_self_time << "</td>\n"
    << "      <td>" << std::setprecision(2) << total_time_percent << "%</td>\n"
    << "      <td>" << std::setprecision(1) << total_time << "</td>\n"
    << "      <td>" << std::setprecision(1) << avg_total_time << "</td>\n"
    << "      <td>" << std::setprecision(1) << worst_total_time << "</td>\n"
    << "    </tr>\n";
  };

  stream()->flags(flags);

  *stream() <<
  "    </tbody>\n"
  "  </table>\n"
  "</body>\n"
  "</html>\n"
  ;
}
开发者ID:ZeroCool1997,项目名称:samp-plugin-profiler,代码行数:101,代码来源:statistics_writer_html.cpp


示例20: _initAndListen

ExitCode _initAndListen(int listenPort) {
    Client::initThread("initandlisten");

    _initWireSpec();
    auto globalServiceContext = getGlobalServiceContext();

    globalServiceContext->setFastClockSource(FastClockSourceFactory::create(Milliseconds(10)));
    globalServiceContext->setOpObserver(stdx::make_unique<OpObserver>());

    DBDirectClientFactory::get(globalServiceContext)
        .registerImplementation([](OperationContext* txn) {
            return std::unique_ptr<DBClientBase>(new DBDirectClient(txn));
        });

    const repl::ReplSettings& replSettings = repl::getGlobalReplicationCoordinator()->getSettings();

    {
        ProcessId pid = ProcessId::getCurrent();
        LogstreamBuilder l = log(LogComponent::kControl);
        l << "MongoDB starting : pid=" << pid << " port=" << serverGlobalParams.port
          << " dbpath=" << storageGlobalParams.dbpath;
        if (replSettings.isMaster())
            l << " master=" << replSettings.isMaster();
        if (replSettings.isSlave())
            l << " slave=" << (int)replSettings.isSlave();

        const bool is32bit = sizeof(int*) == 4;
        l << (is32bit ? " 32" : " 64") << "-bit host=" << getHostNameCached() << endl;
    }

    DEV log(LogComponent::kControl) << "DEBUG build (which is slower)" << endl;

#if defined(_WIN32)
    VersionInfoInterface::instance().logTargetMinOS();
#endif

    logProcessDetails();

    checked_cast<ServiceContextMongoD*>(getGlobalServiceContext())->createLockFile();

    transport::TransportLayerLegacy::Options options;
    options.port = listenPort;
    options.ipList = serverGlobalParams.bind_ip;

    auto sep =
        stdx::make_unique<ServiceEntryPointMongod>(getGlobalServiceContext()->getTransportLayer());
    auto sepPtr = sep.get();

    getGlobalServiceContext()->setServiceEntryPoint(std::move(sep));

    // Create, start, and attach the TL
    auto transportLayer = stdx::make_unique<transport::TransportLayerLegacy>(options, sepPtr);
    auto res = transportLayer->setup();
    if (!res.isOK()) {
        error() << "Failed to set up listener: " << res;
        return EXIT_NET_ERROR;
    }

    std::shared_ptr<DbWebServer> dbWebServer;
    if (serverGlobalParams.isHttpInterfaceEnabled) {
        dbWebServer.reset(new DbWebServer(serverGlobalParams.bind_ip,
                                          serverGlobalParams.port + 1000,
                                          getGlobalServiceContext(),
                                          new RestAdminAccess()));
        if (!dbWebServer->setupSockets()) {
            error() << "Failed to set up sockets for HTTP interface during startup.";
            return EXIT_NET_ERROR;
        }
    }

    getGlobalServiceContext()->initializeGlobalStorageEngine();

#ifdef MONGO_CONFIG_WIREDTIGER_ENABLED
    if (WiredTigerCustomizationHooks::get(getGlobalServiceContext())->restartRequired()) {
        exitCleanly(EXIT_CLEAN);
    }
#endif

    // Warn if we detect configurations for multiple registered storage engines in
    // the same configuration file/environment.
    if (serverGlobalParams.parsedOpts.hasField("storage")) {
        BSONElement storageElement = serverGlobalParams.parsedOpts.getField("storage");
        invariant(storageElement.isABSONObj());
        BSONObj storageParamsObj = storageElement.Obj();
        BSONObjIterator i = storageParamsObj.begin();
        while (i.more()) {
            BSONElement e = i.next();
            // Ignore if field name under "storage" matches current storage engine.
            if (storageGlobalParams.engine == e.fieldName()) {
                continue;
            }

            // Warn if field name matches non-active registered storage engine.
            if (getGlobalServiceContext()->isRegisteredStorageEngine(e.fieldName())) {
                warning() << "Detected configuration for non-active storage engine "
                          << e.fieldName() << " when current storage engine is "
                          << storageGlobalParams.engine;
            }
        }
    }
//.........这里部分代码省略.........
开发者ID:judahschvimer,项目名称:mongo,代码行数:101,代码来源:db.cpp



注:本文中的Milliseconds函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ MiniDumpWriteDump函数代码示例发布时间:2022-05-30
下一篇:
C++ Millimeter2iu函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap