void nsIdleService::ReconfigureTimer(void) { // Check if either someone is idle, or someone will become idle. if (!mAnyObserverIdle && UINT32_MAX == mDeltaToNextIdleSwitchInS) { // If not, just let any existing timers run to completion // And bail out. PR_LOG(sLog, PR_LOG_DEBUG, ("idleService: ReconfigureTimer: no idle or waiting observers")); #ifdef ANDROID __android_log_print(ANDROID_LOG_INFO, "IdleService", "ReconfigureTimer: no idle or waiting observers"); #endif return; } // Find the next timeout value, assuming we are not polling. // We need to store the current time, so we don't get artifacts from the time // ticking while we are processing. TimeStamp curTime = TimeStamp::Now(); TimeStamp nextTimeoutAt = mLastUserInteraction + TimeDuration::FromSeconds(mDeltaToNextIdleSwitchInS); TimeDuration nextTimeoutDuration = nextTimeoutAt - curTime; PR_LOG(sLog, PR_LOG_DEBUG, ("idleService: next timeout %0.f msec from now", nextTimeoutDuration.ToMilliseconds())); #ifdef ANDROID __android_log_print(ANDROID_LOG_INFO, "IdleService", "next timeout %0.f msec from now", nextTimeoutDuration.ToMilliseconds()); #endif // Check if we should correct the timeout time because we should poll before. if (mAnyObserverIdle && UsePollMode()) { TimeStamp pollTimeout = curTime + TimeDuration::FromMilliseconds(MIN_IDLE_POLL_INTERVAL_MSEC); if (nextTimeoutAt > pollTimeout) { PR_LOG(sLog, PR_LOG_DEBUG, ("idleService: idle observers, reducing timeout to %u msec from now", MIN_IDLE_POLL_INTERVAL_MSEC)); #ifdef ANDROID __android_log_print(ANDROID_LOG_INFO, "IdleService", "idle observers, reducing timeout to %u msec from now", MIN_IDLE_POLL_INTERVAL_MSEC); #endif nextTimeoutAt = pollTimeout; } } SetTimerExpiryIfBefore(nextTimeoutAt); }
bool gfxPlatformFontList::LoadFontInfo() { TimeStamp start = TimeStamp::Now(); uint32_t i, endIndex = mNumFamilies; bool loadCmaps = !UsesSystemFallback() || gfxPlatform::GetPlatform()->UseCmapsDuringSystemFallback(); // for each font family, load in various font info for (i = mStartIndex; i < endIndex; i++) { nsAutoString key; gfxFontFamily *familyEntry; GenerateFontListKey(mFontInfo->mFontFamiliesToLoad[i], key); // lookup in canonical (i.e. English) family name list if (!(familyEntry = mFontFamilies.GetWeak(key))) { continue; } // read in face names familyEntry->ReadFaceNames(this, NeedFullnamePostscriptNames(), mFontInfo); // load the cmaps if needed if (loadCmaps) { familyEntry->ReadAllCMAPs(mFontInfo); } // limit the time spent reading fonts in one pass TimeDuration elapsed = TimeStamp::Now() - start; if (elapsed.ToMilliseconds() > FONT_LOADER_MAX_TIMESLICE && i + 1 != endIndex) { endIndex = i + 1; break; } } mStartIndex = endIndex; bool done = mStartIndex >= mNumFamilies; #ifdef PR_LOGGING if (LOG_FONTINIT_ENABLED()) { TimeDuration elapsed = TimeStamp::Now() - start; LOG_FONTINIT(("(fontinit) fontloader load pass %8.2f ms done %s\n", elapsed.ToMilliseconds(), (done ? "true" : "false"))); } #endif if (done) { mOtherFamilyNamesInitialized = true; mFaceNameListsInitialized = true; } return done; }
void TableTicker::Tick(TickSample* sample) { // Marker(s) come before the sample ProfileStack* stack = mPrimaryThreadProfile.GetStack(); for (int i = 0; stack->getMarker(i) != NULL; i++) { mPrimaryThreadProfile.addTag(ProfileEntry('m', stack->getMarker(i))); } stack->mQueueClearMarker = true; bool recordSample = true; if (mJankOnly) { // if we are on a different event we can discard any temporary samples // we've kept around if (sLastSampledEventGeneration != sCurrentEventGeneration) { // XXX: we also probably want to add an entry to the profile to help // distinguish which samples are part of the same event. That, or record // the event generation in each sample mPrimaryThreadProfile.erase(); } sLastSampledEventGeneration = sCurrentEventGeneration; recordSample = false; // only record the events when we have a we haven't seen a tracer event for 100ms if (!sLastTracerEvent.IsNull()) { TimeDuration delta = sample->timestamp - sLastTracerEvent; if (delta.ToMilliseconds() > 100.0) { recordSample = true; } } } #if defined(USE_BACKTRACE) || defined(USE_NS_STACKWALK) || defined(USE_LIBUNWIND) if (mUseStackWalk) { doBacktrace(mPrimaryThreadProfile, sample); } else { doSampleStackTrace(stack, mPrimaryThreadProfile, sample); } #else doSampleStackTrace(stack, mPrimaryThreadProfile, sample); #endif if (recordSample) mPrimaryThreadProfile.flush(); if (!sLastTracerEvent.IsNull() && sample) { TimeDuration delta = sample->timestamp - sLastTracerEvent; mPrimaryThreadProfile.addTag(ProfileEntry('r', delta.ToMilliseconds())); } if (sample) { TimeDuration delta = sample->timestamp - mStartTime; mPrimaryThreadProfile.addTag(ProfileEntry('t', delta.ToMilliseconds())); } }
void VideoCodecStatistics::ReceiveStateChange(const int aChannel, VideoReceiveState aState) { CSFLogDebug(logTag,"New state for %d: %d (was %d)", aChannel, aState, mReceiveState); #ifdef MOZILLA_INTERNAL_API if (mFirstDecodeTime.IsNull()) { mFirstDecodeTime = TimeStamp::Now(); } /* * Invalid transitions: * WaitingKey -> PreemptiveNACK * DecodingWithErrors -> PreemptiveNACK */ switch (mReceiveState) { case kReceiveStateNormal: case kReceiveStateInitial: // in a normal state if (aState != kReceiveStateNormal && aState != kReceiveStateInitial) { // no longer in a normal state if (aState != kReceiveStatePreemptiveNACK) { mReceiveFailureTime = TimeStamp::Now(); } } // else Normal<->Initial transition break; default: // not in a normal state if (aState == kReceiveStateNormal || aState == kReceiveStateInitial) { if (mReceiveState == kReceiveStatePreemptiveNACK) { mRecoveredBeforeLoss++; CSFLogError(logTag, "Video error avoided by NACK recovery"); } else if (!mReceiveFailureTime.IsNull()) { // safety TimeDuration timeDelta = TimeStamp::Now() - mReceiveFailureTime; CSFLogError(logTag, "Video error duration: %u ms", static_cast<uint32_t>(timeDelta.ToMilliseconds())); #if !defined(MOZILLA_XPCOMRT_API) Telemetry::Accumulate(Telemetry::WEBRTC_VIDEO_ERROR_RECOVERY_MS, static_cast<uint32_t>(timeDelta.ToMilliseconds())); #endif // mRecoveredLosses++; // to calculate losses per minute mTotalLossTime += timeDelta; // To calculate % time in recovery } } // else non-Normal to different non-normal transition break; } #endif mReceiveState = aState; }
bool Axis::SampleSnapBack(const TimeDuration& aDelta) { // Apply spring physics to the snap-back as time goes on. // Note: this method of sampling isn't perfectly smooth, as it assumes // a constant velocity over 'aDelta', instead of an accelerating velocity. // (The way we applying friction to flings has the same issue.) // Hooke's law with damping: // F = -kx - bv // where // k is a constant related to the stiffness of the spring // The larger the constant, the stiffer the spring. // x is the displacement of the end of the spring from its equilibrium // In our scenario, it's the amount of overscroll on the axis. // b is a constant that provides damping (friction) // v is the velocity of the point at the end of the spring // See http://gafferongames.com/game-physics/spring-physics/ const float kSpringStiffness = gfxPrefs::APZOverscrollSnapBackSpringStiffness(); const float kSpringFriction = gfxPrefs::APZOverscrollSnapBackSpringFriction(); const float kMass = gfxPrefs::APZOverscrollSnapBackMass(); float force = -1 * kSpringStiffness * mOverscroll - kSpringFriction * mVelocity; float acceleration = force / kMass; mVelocity += acceleration * aDelta.ToMilliseconds(); float screenDisplacement = mVelocity * aDelta.ToMilliseconds(); float cssDisplacement = screenDisplacement / GetFrameMetrics().GetZoom().scale; if (mOverscroll > 0) { if (cssDisplacement > 0) { NS_WARNING("Overscroll snap-back animation is moving in the wrong direction!"); return false; } mOverscroll = std::max(mOverscroll + cssDisplacement, 0.0f); // Overscroll relieved, do not continue animation. if (mOverscroll == 0.f) { mVelocity = 0; return false; } return true; } else if (mOverscroll < 0) { if (cssDisplacement < 0) { NS_WARNING("Overscroll snap-back animation is moving in the wrong direction!"); return false; } mOverscroll = std::min(mOverscroll + cssDisplacement, 0.0f); // Overscroll relieved, do not continue animation. if (mOverscroll == 0.f) { mVelocity = 0; return false; } return true; } // No overscroll on this axis, do not continue animation. return false; }
void RequestContext::RescheduleUntailTimer(TimeStamp const& now) { MOZ_ASSERT(mUntailAt >= now); if (mUntailTimer) { mUntailTimer->Cancel(); } if (!mTailQueue.Length()) { mUntailTimer = nullptr; mTimerScheduledAt = TimeStamp(); return; } TimeDuration interval = mUntailAt - now; if (!mTimerScheduledAt.IsNull() && mUntailAt < mTimerScheduledAt) { // When the number of untailed requests goes down, // let's half the interval, since it's likely we would // reschedule for a shorter time again very soon. // This will likely save rescheduling this timer. interval = interval / int64_t(2); mTimerScheduledAt = mUntailAt - interval; } else { mTimerScheduledAt = mUntailAt; } uint32_t delay = interval.ToMilliseconds(); mUntailTimer = do_CreateInstance("@mozilla.org/timer;1"); mUntailTimer->InitWithCallback(this, delay, nsITimer::TYPE_ONE_SHOT); LOG(("RequestContext::RescheduleUntailTimer %p in %d", this, delay)); }
void AsyncPanZoomController::TrackTouch(const MultiTouchInput& aEvent) { TimeDuration timeDelta = TimeDuration().FromMilliseconds(aEvent.mTime - mLastEventTime); // Probably a duplicate event, just throw it away. if (timeDelta.ToMilliseconds() <= EPSILON) { return; } UpdateWithTouchAtDevicePoint(aEvent); { MonitorAutoLock monitor(mMonitor); // We want to inversely scale it because when you're zoomed further in, a // larger swipe should move you a shorter distance. float inverseScale = 1 / mFrameMetrics.mResolution.width; PRInt32 xDisplacement = mX.GetDisplacementForDuration(inverseScale, timeDelta); PRInt32 yDisplacement = mY.GetDisplacementForDuration(inverseScale, timeDelta); if (!xDisplacement && !yDisplacement) { return; } ScrollBy(nsIntPoint(xDisplacement, yDisplacement)); ScheduleComposite(); if (aEvent.mTime - mLastRepaint >= PAN_REPAINT_INTERVAL) { RequestContentRepaint(); mLastRepaint = aEvent.mTime; } } }
// Iterate the same way we do in GetFPS() void FPSCounter::WriteFrameTimeStamps(PRFileDesc* fd) { const int bufferSize = 256; char buffer[bufferSize]; int writtenCount = SprintfLiteral(buffer, "FPS Data for: %s\n", mFPSName); MOZ_ASSERT(writtenCount >= 0); PR_Write(fd, buffer, writtenCount); ResetReverseIterator(); TimeStamp startTimeStamp = GetLatestTimeStamp(); MOZ_ASSERT(HasNext(startTimeStamp)); TimeStamp previousSample = GetNextTimeStamp(); MOZ_ASSERT(HasNext(startTimeStamp)); TimeStamp nextTimeStamp = GetNextTimeStamp(); while (HasNext(startTimeStamp)) { TimeDuration duration = previousSample - nextTimeStamp; writtenCount = SprintfLiteral(buffer, "%f,\n", duration.ToMilliseconds()); MOZ_ASSERT(writtenCount >= 0); PR_Write(fd, buffer, writtenCount); previousSample = nextTimeStamp; nextTimeStamp = GetNextTimeStamp(); } }
// Iterate the same way we do in GetFPS() int FPSCounter::BuildHistogram(std::map<int, int>& aFpsData) { TimeStamp currentIntervalStart = GetLatestTimeStamp(); TimeStamp currentTimeStamp = GetLatestTimeStamp(); TimeStamp startTimeStamp = GetLatestTimeStamp(); int frameCount = 0; int totalFrameCount = 0; ResetReverseIterator(); while (HasNext(startTimeStamp)) { currentTimeStamp = GetNextTimeStamp(); TimeDuration interval = currentIntervalStart - currentTimeStamp; if (interval.ToSeconds() >= 1.0 ) { currentIntervalStart = currentTimeStamp; aFpsData[frameCount]++; frameCount = 0; } frameCount++; totalFrameCount++; } TimeDuration totalTime = currentIntervalStart - currentTimeStamp; printf_stderr("Discarded %d frames over %f ms in histogram for %s\n", frameCount, totalTime.ToMilliseconds(), mFPSName); return totalFrameCount; }
void mozilla_sampler_add_marker(const char *aMarker, ProfilerMarkerPayload *aPayload) { // Note that aPayload may be allocated by the caller, so we need to make sure // that we free it at some point. nsAutoPtr<ProfilerMarkerPayload> payload(aPayload); if (!stack_key_initialized) return; // Don't insert a marker if we're not profiling to avoid // the heap copy (malloc). if (!profiler_is_active()) { return; } // Don't add a marker if we don't want to include personal information if (profiler_in_privacy_mode()) { return; } PseudoStack *stack = tlsPseudoStack.get(); if (!stack) { return; } TimeDuration delta = TimeStamp::Now() - sStartTime; stack->addMarker(aMarker, payload.forget(), static_cast<float>(delta.ToMilliseconds())); }
void nsDOMNavigationTiming::NotifyNonBlankPaintForRootContentDocument() { MOZ_ASSERT(NS_IsMainThread()); MOZ_ASSERT(!mNavigationStartTimeStamp.IsNull()); if (!mNonBlankPaintTimeStamp.IsNull()) { return; } mNonBlankPaintTimeStamp = TimeStamp::Now(); TimeDuration elapsed = mNonBlankPaintTimeStamp - mNavigationStartTimeStamp; if (profiler_is_active()) { nsAutoCString spec; if (mLoadedURI) { mLoadedURI->GetSpec(spec); } nsPrintfCString marker("Non-blank paint after %dms for URL %s, %s", int(elapsed.ToMilliseconds()), spec.get(), mDocShellHasBeenActiveSinceNavigationStart ? "foreground tab" : "this tab was inactive some of the time between navigation start and first non-blank paint"); profiler_add_marker(marker.get()); } if (mDocShellHasBeenActiveSinceNavigationStart) { Telemetry::AccumulateTimeDelta(Telemetry::TIME_TO_NON_BLANK_PAINT_MS, mNavigationStartTimeStamp, mNonBlankPaintTimeStamp); } }
PLDHashOperator gfxPlatformFontList::ReadFaceNamesProc(nsStringHashKey::KeyType aKey, nsRefPtr<gfxFontFamily>& aFamilyEntry, void* userArg) { ReadFaceNamesData *data = static_cast<ReadFaceNamesData*>(userArg); gfxPlatformFontList *fc = data->mFontList; // when filtering, skip names that don't start with the filter character if (!(data->mFirstChar.IsEmpty())) { char16_t firstChar = aKey.CharAt(0); nsAutoString firstCharStr(&firstChar, 1); ToLowerCase(firstCharStr); if (!firstCharStr.Equals(data->mFirstChar)) { return PL_DHASH_NEXT; } } aFamilyEntry->ReadFaceNames(fc, fc->NeedFullnamePostscriptNames()); TimeDuration elapsed = TimeStamp::Now() - data->mStartTime; if (elapsed.ToMilliseconds() > NAMELIST_TIMEOUT) { data->mTimedOut = true; return PL_DHASH_STOP; } return PL_DHASH_NEXT; }
void CompositorParent::ScheduleComposition() { if (mCurrentCompositeTask || mPaused) { return; } bool initialComposition = mLastCompose.IsNull(); TimeDuration delta; if (!initialComposition) delta = TimeStamp::Now() - mLastCompose; int32_t rate = CalculateCompositionFrameRate(); // If rate == 0 (ASAP mode), minFrameDelta must be 0 so there's no delay. TimeDuration minFrameDelta = TimeDuration::FromMilliseconds( rate == 0 ? 0.0 : std::max(0.0, 1000.0 / rate)); mCurrentCompositeTask = NewRunnableMethod(this, &CompositorParent::CompositeCallback); if (!initialComposition && delta < minFrameDelta) { TimeDuration delay = minFrameDelta - delta; #ifdef COMPOSITOR_PERFORMANCE_WARNING mExpectedComposeStartTime = TimeStamp::Now() + delay; #endif ScheduleTask(mCurrentCompositeTask, delay.ToMilliseconds()); } else { #ifdef COMPOSITOR_PERFORMANCE_WARNING mExpectedComposeStartTime = TimeStamp::Now(); #endif ScheduleTask(mCurrentCompositeTask, 0); } }
static void RecordShutdownEndTimeStamp() { if (!gRecordedShutdownTimeFileName) return; nsCString name(gRecordedShutdownTimeFileName); PL_strfree(gRecordedShutdownTimeFileName); gRecordedShutdownTimeFileName = NULL; nsCString tmpName = name; tmpName += ".tmp"; PRFileDesc *f = PR_Open(tmpName.get(), PR_CREATE_FILE | PR_WRONLY, PR_IRUSR | PR_IWUSR); if (!f) return; TimeStamp now = TimeStamp::Now(); MOZ_ASSERT(now >= gRecordedShutdownStartTime); TimeDuration diff = now - gRecordedShutdownStartTime; uint32_t diff2 = diff.ToMilliseconds(); uint32_t written = PR_fprintf(f, "%d\n", diff2); PRStatus rv = PR_Close(f); if (written == static_cast<uint32_t>(-1) || rv != PR_SUCCESS) { PR_Delete(tmpName.get()); return; } PR_Rename(tmpName.get(), name.get()); }
void Axis::UpdateWithTouchAtDevicePoint(int32_t aPos, const TimeDuration& aTimeDelta) { if (mPos == aPos) { // Does not make sense to calculate velocity when distance is 0 return; } float newVelocity = (mPos - aPos) / aTimeDelta.ToMilliseconds(); bool curVelocityBelowThreshold = fabsf(newVelocity) < gVelocityThreshold; bool directionChange = (mVelocity > 0) != (newVelocity > 0); // If we've changed directions, or the current velocity threshold, stop any // acceleration we've accumulated. if (directionChange || curVelocityBelowThreshold) { mAcceleration = 0; } mVelocity = newVelocity; mPos = aPos; // Keep last gMaxVelocityQueueSize or less velocities in the queue. mVelocityQueue.AppendElement(mVelocity); if (mVelocityQueue.Length() > gMaxVelocityQueueSize) { mVelocityQueue.RemoveElementAt(0); } }
DOMHighResTimeStamp Performance::Now() const { TimeDuration duration = TimeStamp::Now() - mWorkerPrivate->CreationTimeStamp(); return RoundTime(duration.ToMilliseconds()); }
gfxFontEntry* gfxPlatformFontList::SearchFamiliesForFaceName(const nsAString& aFaceName) { TimeStamp start = TimeStamp::Now(); gfxFontEntry *lookup = nullptr; ReadFaceNamesData faceNameListsData(this, start); // iterate over familes starting with the same letter faceNameListsData.mFirstChar = ToLowerCase(aFaceName.CharAt(0)); mFontFamilies.Enumerate(gfxPlatformFontList::ReadFaceNamesProc, &faceNameListsData); lookup = FindFaceName(aFaceName); TimeStamp end = TimeStamp::Now(); Telemetry::AccumulateTimeDelta(Telemetry::FONTLIST_INITFACENAMELISTS, start, end); #ifdef PR_LOGGING if (LOG_FONTINIT_ENABLED()) { TimeDuration elapsed = end - start; LOG_FONTINIT(("(fontinit) SearchFamiliesForFaceName took %8.2f ms %s %s", elapsed.ToMilliseconds(), (lookup ? "found name" : ""), (faceNameListsData.mTimedOut ? "timeout" : ""))); } #endif return lookup; }
//WebRTC::RTP Callback Implementation // Called on AudioGUM or MSG thread int WebrtcAudioConduit::SendPacket(int channel, const void* data, int len) { CSFLogDebug(logTag, "%s : channel %d", __FUNCTION__, channel); #if !defined(MOZILLA_EXTERNAL_LINKAGE) if (PR_LOG_TEST(GetLatencyLog(), PR_LOG_DEBUG)) { if (mProcessing.Length() > 0) { TimeStamp started = mProcessing[0].mTimeStamp; mProcessing.RemoveElementAt(0); mProcessing.RemoveElementAt(0); // 20ms packetization! Could automate this by watching sizes TimeDuration t = TimeStamp::Now() - started; int64_t delta = t.ToMilliseconds(); LogTime(AsyncLatencyLogger::AudioSendRTP, ((uint64_t) this), delta); } } #endif ReentrantMonitorAutoEnter enter(mTransportMonitor); if(mTransmitterTransport && (mTransmitterTransport->SendRtpPacket(data, len) == NS_OK)) { CSFLogDebug(logTag, "%s Sent RTP Packet ", __FUNCTION__); return len; } else { CSFLogError(logTag, "%s RTP Packet Send Failed ", __FUNCTION__); return -1; } }
void gfxPlatformFontList::InitOtherFamilyNames() { if (mOtherFamilyNamesInitialized) { return; } TimeStamp start = TimeStamp::Now(); // iterate over all font families and read in other family names InitOtherNamesData otherNamesData(this, start); mFontFamilies.Enumerate(gfxPlatformFontList::InitOtherFamilyNamesProc, &otherNamesData); if (!otherNamesData.mTimedOut) { mOtherFamilyNamesInitialized = true; } TimeStamp end = TimeStamp::Now(); Telemetry::AccumulateTimeDelta(Telemetry::FONTLIST_INITOTHERFAMILYNAMES, start, end); #ifdef PR_LOGGING if (LOG_FONTINIT_ENABLED()) { TimeDuration elapsed = end - start; LOG_FONTINIT(("(fontinit) InitOtherFamilyNames took %8.2f ms %s", elapsed.ToMilliseconds(), (otherNamesData.mTimedOut ? "timeout" : ""))); } #endif }
double Performance::Now() const { TimeDuration duration = TimeStamp::Now() - mWorkerPrivate->NowBaseTimeStamp(); return duration.ToMilliseconds(); }
void TableTicker::Tick(TickSample* sample) { // Marker(s) come before the sample int i = 0; const char *marker = mStack->getMarker(i++); for (int i = 0; marker != NULL; i++) { mProfile.addTag(ProfileEntry('m', marker)); marker = mStack->getMarker(i++); } mStack->mQueueClearMarker = true; // Sample // 's' tag denotes the start of a sample block // followed by 0 or more 'c' tags. for (int i = 0; i < mStack->mStackPointer; i++) { if (i == 0) { Address pc = 0; if (sample) { pc = sample->pc; } mProfile.addTag(ProfileEntry('s', mStack->mStack[i], pc)); } else { mProfile.addTag(ProfileEntry('c', mStack->mStack[i])); } } if (!sLastTracerEvent.IsNull()) { TimeDuration delta = TimeStamp::Now() - sLastTracerEvent; mProfile.addTag(ProfileEntry('r', delta.ToMilliseconds())); } }
bool VsyncParent::RecvRequestVsyncRate() { AssertIsOnBackgroundThread(); TimeDuration vsyncRate = gfxPlatform::GetPlatform()->GetHardwareVsync()->GetGlobalDisplay().GetVsyncRate(); Unused << SendVsyncRate(vsyncRate.ToMilliseconds()); return true; }
gfxFontEntry* gfxPlatformFontList::SearchFamiliesForFaceName(const nsAString& aFaceName) { TimeStamp start = TimeStamp::Now(); bool timedOut = false; // if mFirstChar is not 0, only load facenames for families // that start with this character char16_t firstChar = 0; gfxFontEntry *lookup = nullptr; // iterate over familes starting with the same letter firstChar = ToLowerCase(aFaceName.CharAt(0)); for (auto iter = mFontFamilies.Iter(); !iter.Done(); iter.Next()) { nsStringHashKey::KeyType key = iter.Key(); nsRefPtr<gfxFontFamily>& family = iter.Data(); // when filtering, skip names that don't start with the filter character if (firstChar && ToLowerCase(key.CharAt(0)) != firstChar) { continue; } family->ReadFaceNames(this, NeedFullnamePostscriptNames()); TimeDuration elapsed = TimeStamp::Now() - start; if (elapsed.ToMilliseconds() > NAMELIST_TIMEOUT) { timedOut = true; break; } } lookup = FindFaceName(aFaceName); TimeStamp end = TimeStamp::Now(); Telemetry::AccumulateTimeDelta(Telemetry::FONTLIST_INITFACENAMELISTS, start, end); if (LOG_FONTINIT_ENABLED()) { TimeDuration elapsed = end - start; LOG_FONTINIT(("(fontinit) SearchFamiliesForFaceName took %8.2f ms %s %s", elapsed.ToMilliseconds(), (lookup ? "found name" : ""), (timedOut ? "timeout" : ""))); } return lookup; }
void DecoderCallbackFuzzingWrapper::SetVideoOutputMinimumInterval( TimeDuration aFrameOutputMinimumInterval) { CFW_LOGD("aFrameOutputMinimumInterval=%fms", aFrameOutputMinimumInterval.ToMilliseconds()); mFrameOutputMinimumInterval = aFrameOutputMinimumInterval; }
double mozilla_sampler_time() { if (!mozilla_sampler_is_active()) { return 0.0; } TimeDuration delta = TimeStamp::Now() - sStartTime; return delta.ToMilliseconds(); }
double mozilla_sampler_time(const TimeStamp& aTime) { if (!mozilla_sampler_is_active()) { return 0.0; } TimeDuration delta = aTime - sStartTime; return delta.ToMilliseconds(); }
void nsHostResolver::ThreadFunc(void *arg) { LOG(("DNS lookup thread starting execution.\n")); static nsThreadPoolNaming naming; naming.SetThreadPoolName(NS_LITERAL_CSTRING("DNS Resolver")); #if defined(RES_RETRY_ON_FAILURE) nsResState rs; #endif nsHostResolver *resolver = (nsHostResolver *)arg; nsHostRecord *rec; PRAddrInfo *prai = nullptr; while (resolver->GetHostToLookup(&rec)) { LOG(("Calling getaddrinfo for host [%s].\n", rec->host)); int flags = PR_AI_ADDRCONFIG; if (!(rec->flags & RES_CANON_NAME)) flags |= PR_AI_NOCANONNAME; TimeStamp startTime = TimeStamp::Now(); prai = PR_GetAddrInfoByName(rec->host, rec->af, flags); #if defined(RES_RETRY_ON_FAILURE) if (!prai && rs.Reset()) prai = PR_GetAddrInfoByName(rec->host, rec->af, flags); #endif TimeDuration elapsed = TimeStamp::Now() - startTime; uint32_t millis = static_cast<uint32_t>(elapsed.ToMilliseconds()); // convert error code to nsresult nsresult status; AddrInfo *ai = nullptr; if (prai) { ai = new AddrInfo(rec->host, prai); PR_FreeAddrInfo(prai); status = NS_OK; Telemetry::Accumulate(!rec->addr_info_gencnt ? Telemetry::DNS_LOOKUP_TIME : Telemetry::DNS_RENEWAL_TIME, millis); } else { status = NS_ERROR_UNKNOWN_HOST; Telemetry::Accumulate(Telemetry::DNS_FAILED_LOOKUP_TIME, millis); } // OnLookupComplete may release "rec", log before we lose it. LOG(("Lookup completed for host [%s].\n", rec->host)); resolver->OnLookupComplete(rec, status, ai); } NS_RELEASE(resolver); LOG(("DNS lookup thread ending execution.\n")); }
// static void RuntimeService::ShutdownIdleThreads(nsITimer* aTimer, void* /* aClosure */) { AssertIsOnMainThread(); RuntimeService* runtime = RuntimeService::GetService(); NS_ASSERTION(runtime, "This should never be null!"); NS_ASSERTION(aTimer == runtime->mIdleThreadTimer, "Wrong timer!"); // Cheat a little and grab all threads that expire within one second of now. TimeStamp now = TimeStamp::Now() + TimeDuration::FromSeconds(1); TimeStamp nextExpiration; nsAutoTArray<nsCOMPtr<nsIThread>, 20> expiredThreads; { MutexAutoLock lock(runtime->mMutex); for (PRUint32 index = 0; index < runtime->mIdleThreadArray.Length(); index++) { IdleThreadInfo& info = runtime->mIdleThreadArray[index]; if (info.mExpirationTime > now) { nextExpiration = info.mExpirationTime; break; } nsCOMPtr<nsIThread>* thread = expiredThreads.AppendElement(); thread->swap(info.mThread); } if (!expiredThreads.IsEmpty()) { runtime->mIdleThreadArray.RemoveElementsAt(0, expiredThreads.Length()); } } NS_ASSERTION(nextExpiration.IsNull() || !expiredThreads.IsEmpty(), "Should have a new time or there should be some threads to shut " "down"); for (PRUint32 index = 0; index < expiredThreads.Length(); index++) { if (NS_FAILED(expiredThreads[index]->Shutdown())) { NS_WARNING("Failed to shutdown thread!"); } } if (!nextExpiration.IsNull()) { TimeDuration delta = nextExpiration - TimeStamp::Now(); PRUint32 delay(delta > TimeDuration(0) ? delta.ToMilliseconds() : 0); // Reschedule the timer. if (NS_FAILED(aTimer->InitWithFuncCallback(ShutdownIdleThreads, nsnull, delay, nsITimer::TYPE_ONE_SHOT))) { NS_ERROR("Can't schedule timer!"); } } }
// This code used to live inside AudioStream::Init(), but on Mac (others?) // it has been known to take 300-800 (or even 8500) ms to execute(!) nsresult AudioStream::OpenCubeb(cubeb_stream_params &aParams) { cubeb* cubebContext = CubebUtils::GetCubebContext(); if (!cubebContext) { NS_WARNING("Can't get cubeb context!"); MonitorAutoLock mon(mMonitor); mState = AudioStream::ERRORED; return NS_ERROR_FAILURE; } // If the latency pref is set, use it. Otherwise, if this stream is intended // for low latency playback, try to get the lowest latency possible. // Otherwise, for normal streams, use 100ms. uint32_t latency = CubebUtils::GetCubebLatency(); { cubeb_stream* stream; if (cubeb_stream_init(cubebContext, &stream, "AudioStream", nullptr, nullptr, nullptr, &aParams, latency, DataCallback_S, StateCallback_S, this) == CUBEB_OK) { MonitorAutoLock mon(mMonitor); MOZ_ASSERT(mState != SHUTDOWN); mCubebStream.reset(stream); } else { MonitorAutoLock mon(mMonitor); mState = ERRORED; NS_WARNING(nsPrintfCString("AudioStream::OpenCubeb() %p failed to init cubeb", this).get()); return NS_ERROR_FAILURE; } } mState = INITIALIZED; if (!mStartTime.IsNull()) { TimeDuration timeDelta = TimeStamp::Now() - mStartTime; LOG("creation time %sfirst: %u ms", mIsFirst ? "" : "not ", (uint32_t) timeDelta.ToMilliseconds()); Telemetry::Accumulate(mIsFirst ? Telemetry::AUDIOSTREAM_FIRST_OPEN_MS : Telemetry::AUDIOSTREAM_LATER_OPEN_MS, timeDelta.ToMilliseconds()); } return NS_OK; }
DOMTimeMilliSec nsDOMNavigationTiming::TimeStampToDOM(TimeStamp aStamp) const { if (aStamp.IsNull()) { return 0; } TimeDuration duration = aStamp - mNavigationStartTimeStamp; return GetNavigationStart() + static_cast<int64_t>(duration.ToMilliseconds()); }