Report post-page load CPU usage using diagnostic logging
authorcdumez@apple.com <cdumez@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 13 Jan 2017 17:54:53 +0000 (17:54 +0000)
committercdumez@apple.com <cdumez@apple.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Fri, 13 Jan 2017 17:54:53 +0000 (17:54 +0000)
https://bugs.webkit.org/show_bug.cgi?id=166950
<rdar://problem/30014496>

Reviewed by Alex Christensen.

Shortly after page load (5 seconds), we measure the WebContent process'
CPU usage over 10 seconds and report the percentage back via release
logging. We also log the percentage using diagnostic logging using the
following buckets:
- Below 10%
- 10 to 20%
- 20 to 40%
- 60 to 80%
- Over 80%

The logging works on both Mac and iOS. I verified that I get results
consistent with Activity Monitor or top.

No new tests, no Web-facing behavior change, only extra logging.

* CMakeLists.txt:
* WebCore.xcodeproj/project.pbxproj:
* loader/FrameLoader.cpp:
(WebCore::FrameLoader::checkLoadCompleteForThisFrame):
* page/DiagnosticLoggingKeys.cpp:
(WebCore::DiagnosticLoggingKeys::postPageLoadKey):
(WebCore::DiagnosticLoggingKeys::cpuUsageKey):
* page/DiagnosticLoggingKeys.h:
* page/Page.cpp:
(WebCore::Page::Page):
(WebCore::Page::didFinishLoad):
(WebCore::cpuUsageToDiagnosticLogginKey):
(WebCore::Page::measurePostLoadCPUUsage):
* page/Page.h:
* page/Settings.cpp:
(WebCore::Settings::isPostLoadCPUUsageMeasurementEnabled):
* page/Settings.h:
* platform/CPUTime.cpp: Added.
(WebCore::getCPUTime):
(WebCore::CPUTime::percentageCPUUsageSince):
* platform/CPUTime.h: Added.
* platform/cocoa/CPUTimeCocoa.mm: Added.
(WebCore::timeValueToMicroseconds):
(WebCore::getCPUTime):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@210733 268f45cc-cd09-0410-ab3c-d52691b4dbfc

13 files changed:
Source/WebCore/CMakeLists.txt
Source/WebCore/ChangeLog
Source/WebCore/WebCore.xcodeproj/project.pbxproj
Source/WebCore/loader/FrameLoader.cpp
Source/WebCore/page/DiagnosticLoggingKeys.cpp
Source/WebCore/page/DiagnosticLoggingKeys.h
Source/WebCore/page/Page.cpp
Source/WebCore/page/Page.h
Source/WebCore/page/Settings.cpp
Source/WebCore/page/Settings.h
Source/WebCore/platform/CPUTime.cpp [new file with mode: 0644]
Source/WebCore/platform/CPUTime.h [new file with mode: 0644]
Source/WebCore/platform/cocoa/CPUTimeCocoa.mm [new file with mode: 0644]

index 3891e64..580d072 100644 (file)
@@ -2054,6 +2054,7 @@ set(WebCore_SOURCES
     page/scrolling/ScrollingTreeScrollingNode.cpp
     page/scrolling/ThreadedScrollingTree.cpp
 
+    platform/CPUTime.cpp
     platform/CalculationValue.cpp
     platform/Clock.cpp
     platform/ClockGeneric.cpp
index 16a5332..1d4ac7b 100644 (file)
@@ -1,3 +1,51 @@
+2017-01-13  Chris Dumez  <cdumez@apple.com>
+
+        Report post-page load CPU usage using diagnostic logging
+        https://bugs.webkit.org/show_bug.cgi?id=166950
+        <rdar://problem/30014496>
+
+        Reviewed by Alex Christensen.
+
+        Shortly after page load (5 seconds), we measure the WebContent process'
+        CPU usage over 10 seconds and report the percentage back via release
+        logging. We also log the percentage using diagnostic logging using the
+        following buckets:
+        - Below 10%
+        - 10 to 20%
+        - 20 to 40%
+        - 60 to 80%
+        - Over 80%
+
+        The logging works on both Mac and iOS. I verified that I get results
+        consistent with Activity Monitor or top.
+
+        No new tests, no Web-facing behavior change, only extra logging.
+
+        * CMakeLists.txt:
+        * WebCore.xcodeproj/project.pbxproj:
+        * loader/FrameLoader.cpp:
+        (WebCore::FrameLoader::checkLoadCompleteForThisFrame):
+        * page/DiagnosticLoggingKeys.cpp:
+        (WebCore::DiagnosticLoggingKeys::postPageLoadKey):
+        (WebCore::DiagnosticLoggingKeys::cpuUsageKey):
+        * page/DiagnosticLoggingKeys.h:
+        * page/Page.cpp:
+        (WebCore::Page::Page):
+        (WebCore::Page::didFinishLoad):
+        (WebCore::cpuUsageToDiagnosticLogginKey):
+        (WebCore::Page::measurePostLoadCPUUsage):
+        * page/Page.h:
+        * page/Settings.cpp:
+        (WebCore::Settings::isPostLoadCPUUsageMeasurementEnabled):
+        * page/Settings.h:
+        * platform/CPUTime.cpp: Added.
+        (WebCore::getCPUTime):
+        (WebCore::CPUTime::percentageCPUUsageSince):
+        * platform/CPUTime.h: Added.
+        * platform/cocoa/CPUTimeCocoa.mm: Added.
+        (WebCore::timeValueToMicroseconds):
+        (WebCore::getCPUTime):
+
 2017-01-13  Michael Catanzaro  <mcatanzaro@igalia.com>
 
         Unreviewed, rolling out r210677.
index 489f436..a9bb8d4 100644 (file)
                460CBF351D4BCD0E0092E88E /* JSDOMWindowProperties.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 460CBF331D4BCCFE0092E88E /* JSDOMWindowProperties.cpp */; };
                460CBF361D4BCD0E0092E88E /* JSDOMWindowProperties.h in Headers */ = {isa = PBXBuildFile; fileRef = 460CBF341D4BCCFE0092E88E /* JSDOMWindowProperties.h */; };
                4634592C1AC2271000ECB71C /* PowerObserverMac.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 4634592B1AC2271000ECB71C /* PowerObserverMac.cpp */; };
+               463763081E26FDD7008CD46D /* CPUTime.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 463763061E26FDBA008CD46D /* CPUTime.cpp */; };
+               463763091E26FDD7008CD46D /* CPUTime.h in Headers */ = {isa = PBXBuildFile; fileRef = 463763071E26FDBA008CD46D /* CPUTime.h */; settings = {ATTRIBUTES = (Private, ); }; };
+               4637630B1E26FDF6008CD46D /* CPUTimeCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 4637630A1E26FDEB008CD46D /* CPUTimeCocoa.mm */; };
                463EB6221B8789E00096ED51 /* TagCollection.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 463EB6201B8789CB0096ED51 /* TagCollection.cpp */; };
                463EB6231B8789E00096ED51 /* TagCollection.h in Headers */ = {isa = PBXBuildFile; fileRef = 463EB6211B8789CB0096ED51 /* TagCollection.h */; };
                465307D01DB6EE4800E4137C /* JSUIEventInit.h in Headers */ = {isa = PBXBuildFile; fileRef = 83E045EF1DAA104F00B0D8B9 /* JSUIEventInit.h */; };
                460CBF331D4BCCFE0092E88E /* JSDOMWindowProperties.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSDOMWindowProperties.cpp; sourceTree = "<group>"; };
                460CBF341D4BCCFE0092E88E /* JSDOMWindowProperties.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSDOMWindowProperties.h; sourceTree = "<group>"; };
                4634592B1AC2271000ECB71C /* PowerObserverMac.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = PowerObserverMac.cpp; sourceTree = "<group>"; };
+               463763061E26FDBA008CD46D /* CPUTime.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CPUTime.cpp; sourceTree = "<group>"; };
+               463763071E26FDBA008CD46D /* CPUTime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CPUTime.h; sourceTree = "<group>"; };
+               4637630A1E26FDEB008CD46D /* CPUTimeCocoa.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = CPUTimeCocoa.mm; sourceTree = "<group>"; };
                463EB6201B8789CB0096ED51 /* TagCollection.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TagCollection.cpp; sourceTree = "<group>"; };
                463EB6211B8789CB0096ED51 /* TagCollection.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TagCollection.h; sourceTree = "<group>"; };
                465A8E781C8A24CE00E7D3E4 /* RuntimeApplicationChecks.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RuntimeApplicationChecks.mm; sourceTree = "<group>"; };
                A5C974CE11485FDA0066F2AB /* cocoa */ = {
                        isa = PBXGroup;
                        children = (
+                               4637630A1E26FDEB008CD46D /* CPUTimeCocoa.mm */,
                                A14090FA1AA51E1D0091191A /* ContentFilterUnblockHandlerCocoa.mm */,
                                CD7D33451C7A16BF00041293 /* CoreVideoSoftLink.cpp */,
                                CD7D33461C7A16BF00041293 /* CoreVideoSoftLink.h */,
                                653EF83619A043AE0052202C /* spi */,
                                1A2E6E560CC551E0004A2062 /* sql */,
                                B2C3D9EC0D006C1D00EF6F26 /* text */,
+                               463763061E26FDBA008CD46D /* CPUTime.cpp */,
+                               463763071E26FDBA008CD46D /* CPUTime.h */,
                                49AE2D94134EE5F90072920A /* CalculationValue.cpp */,
                                49AE2D95134EE5F90072920A /* CalculationValue.h */,
                                CDEA76331460B462008B31F1 /* Clock.cpp */,
                                5B30695E18B3D3450099D5E8 /* WebGLDrawBuffers.h in Headers */,
                                6EBF0E5512A8929800DB1709 /* WebGLExtension.h in Headers */,
                                49C7B9CF1042D32F0009D447 /* WebGLFramebuffer.h in Headers */,
+                               463763091E26FDD7008CD46D /* CPUTime.h in Headers */,
                                6E47E66110B7944B00B186C8 /* WebGLAny.h in Headers */,
                                49FFBF3F11C93EE3006A7118 /* WebGLLayer.h in Headers */,
                                93F1D5BB12D532C400832BEC /* WebGLLoseContext.h in Headers */,
                                2E0888D41148848A00AF4265 /* JSDOMFormData.cpp in Sources */,
                                E1C36CBD0EB08062007410BC /* JSDOMGlobalObject.cpp in Sources */,
                                7C2BDD3D17C7F98C0038FF15 /* JSDOMGlobalObjectTask.cpp in Sources */,
+                               463763081E26FDD7008CD46D /* CPUTime.cpp in Sources */,
                                65DF31F709D1CC60000BE325 /* JSDOMImplementation.cpp in Sources */,
                                9479493C1E045CF300018D85 /* DeprecatedCSSOMPrimitiveValue.cpp in Sources */,
                                4138F8571D253F08001CB61E /* JSDOMIterator.cpp in Sources */,
                                BC06ED9F0BFD660600856E9D /* JSHTMLTableRowElement.cpp in Sources */,
                                BC06ED060BFD5BAE00856E9D /* JSHTMLTableSectionElement.cpp in Sources */,
                                D6489D25166FFCF1007C031B /* JSHTMLTemplateElement.cpp in Sources */,
+                               4637630B1E26FDF6008CD46D /* CPUTimeCocoa.mm in Sources */,
                                D6F7960D166FFECE0076DD18 /* JSHTMLTemplateElementCustom.cpp in Sources */,
                                A80E7E9E0A1A83E3007FB8C5 /* JSHTMLTextAreaElement.cpp in Sources */,
                                83E359A31BB1031D002CEB98 /* JSHTMLTimeElement.cpp in Sources */,
index 0bc7f87..4cfebef 100644 (file)
@@ -991,6 +991,11 @@ void FrameLoader::provisionalLoadStarted()
         m_stateMachine.advanceTo(FrameLoaderStateMachine::CommittedFirstRealLoad);
     m_frame.navigationScheduler().cancel(true);
     m_client.provisionalLoadStarted();
+
+    if (m_frame.isMainFrame()) {
+        if (auto* page = m_frame.page())
+            page->didStartProvisionalLoad();
+    }
 }
 
 void FrameLoader::resetMultipleFormSubmissionProtection()
@@ -2286,7 +2291,7 @@ void FrameLoader::checkLoadCompleteForThisFrame()
             Page* page = m_frame.page();
             if (page) {
                 if (m_frame.isMainFrame())
-                    page->resetRelevantPaintedObjectCounter();
+                    page->didFinishLoad();
             }
 
             const ResourceError& error = dl->mainDocumentError();
index d6be020..0fa2664 100644 (file)
@@ -53,6 +53,11 @@ String DiagnosticLoggingKeys::pluginLoadingFailedKey()
     return ASCIILiteral("pluginFailedLoading");
 }
 
+String DiagnosticLoggingKeys::postPageLoadKey()
+{
+    return ASCIILiteral("postPageLoad");
+}
+
 String DiagnosticLoggingKeys::provisionalLoadKey()
 {
     return ASCIILiteral("provisionalLoad");
@@ -303,6 +308,11 @@ String DiagnosticLoggingKeys::cannotSuspendActiveDOMObjectsKey()
     return ASCIILiteral("cannotSuspendActiveDOMObjects");
 }
 
+String DiagnosticLoggingKeys::cpuUsageKey()
+{
+    return ASCIILiteral("cpuUsage");
+}
+
 String DiagnosticLoggingKeys::createSharedBufferFailedKey()
 {
     return ASCIILiteral("createSharedBufferFailed");
index 2ee627b..c7531c6 100644 (file)
@@ -38,6 +38,7 @@ public:
     static String cachedResourceRevalidationKey();
     static String canCacheKey();
     static String cannotSuspendActiveDOMObjectsKey();
+    static String cpuUsageKey();
     WEBCORE_EXPORT static String createSharedBufferFailedKey();
     WEBCORE_EXPORT static String deltaKey();
     static String deniedByClientKey();
@@ -97,6 +98,7 @@ public:
     static String playedKey();
     static String pluginLoadedKey();
     static String pluginLoadingFailedKey();
+    static String postPageLoadKey();
     static String provisionalLoadKey();
     static String prunedDueToMaxSizeReached();
     static String prunedDueToMemoryPressureKey();
index 9331b30..c79194a 100644 (file)
@@ -33,6 +33,7 @@
 #include "ContextMenuController.h"
 #include "DatabaseProvider.h"
 #include "DiagnosticLoggingClient.h"
+#include "DiagnosticLoggingKeys.h"
 #include "DocumentLoader.h"
 #include "DocumentMarkerController.h"
 #include "DragController.h"
@@ -98,6 +99,7 @@
 #include "VisitedLinkStore.h"
 #include "VoidCallback.h"
 #include "Widget.h"
+#include <wtf/CurrentTime.h>
 #include <wtf/RefCountedLeakCounter.h>
 #include <wtf/StdLibExtras.h>
 #include <wtf/text/Base64.h>
 
 namespace WebCore {
 
+#define RELEASE_LOG_IF_ALLOWED(channel, fmt, ...) RELEASE_LOG_IF(isAlwaysOnLoggingAllowed(), channel, "%p - Page::" fmt, this, ##__VA_ARGS__)
+
 static HashSet<Page*>* allPages;
 
+static const std::chrono::seconds cpuUsageMeasurementDelay { 5 };
+static const std::chrono::seconds cpuUsageMeasurementDuration { 10 };
+
 DEFINE_DEBUG_ONLY_GLOBAL(WTF::RefCountedLeakCounter, pageCounter, ("Page"));
 
 void Page::forEachPage(std::function<void(Page&)> function)
@@ -244,6 +251,7 @@ Page::Page(PageConfiguration&& pageConfiguration)
     , m_visitedLinkStore(*WTFMove(pageConfiguration.visitedLinkStore))
     , m_sessionID(SessionID::defaultSessionID())
     , m_isClosing(false)
+    , m_cpuUsageMeasurementTimer(*this, &Page::measurePostLoadCPUUsage)
 {
     updateTimerThrottlingState();
 
@@ -920,6 +928,55 @@ void Page::setUserInterfaceLayoutDirection(UserInterfaceLayoutDirection userInte
 #endif
 }
 
+void Page::didStartProvisionalLoad()
+{
+    m_postLoadCPUTime = std::nullopt;
+    m_cpuUsageMeasurementTimer.stop();
+}
+
+void Page::didFinishLoad()
+{
+    resetRelevantPaintedObjectCounter();
+
+    // Only do post-load CPU usage measurement if there is a single Page in the process in order to reduce noise.
+    if (Settings::isPostLoadCPUUsageMeasurementEnabled() && allPages->size() == 1) {
+        m_postLoadCPUTime = std::nullopt;
+        m_cpuUsageMeasurementTimer.startOneShot(cpuUsageMeasurementDelay);
+    }
+}
+
+static String cpuUsageToDiagnosticLogginKey(double cpuUsage)
+{
+    if (cpuUsage < 10)
+        return ASCIILiteral("Below10");
+    if (cpuUsage < 20)
+        return ASCIILiteral("10to20");
+    if (cpuUsage < 40)
+        return ASCIILiteral("20to40");
+    if (cpuUsage < 60)
+        return ASCIILiteral("40to60");
+    if (cpuUsage < 80)
+        return ASCIILiteral("60to80");
+    return ASCIILiteral("over80");
+}
+
+void Page::measurePostLoadCPUUsage()
+{
+    if (!m_postLoadCPUTime) {
+        m_postLoadCPUTime = getCPUTime();
+        if (m_postLoadCPUTime)
+            m_cpuUsageMeasurementTimer.startOneShot(cpuUsageMeasurementDuration);
+        return;
+    }
+    std::optional<CPUTime> cpuTime = getCPUTime();
+    if (!cpuTime)
+        return;
+
+    double cpuUsage = cpuTime.value().percentageCPUUsageSince(*m_postLoadCPUTime);
+    RELEASE_LOG_IF_ALLOWED(PerformanceLogging, "measurePostLoadCPUUsage: Process was using %.1f%% percent CPU after the page load.", cpuUsage);
+    diagnosticLoggingClient().logDiagnosticMessageWithValue(DiagnosticLoggingKeys::postPageLoadKey(), DiagnosticLoggingKeys::cpuUsageKey(), cpuUsageToDiagnosticLogginKey(cpuUsage), ShouldSample::No);
+}
+
 void Page::setTopContentInset(float contentInset)
 {
     if (m_topContentInset == contentInset)
index de3fe4e..18164d3 100644 (file)
@@ -21,6 +21,7 @@
 #pragma once
 
 #include "ActivityState.h"
+#include "CPUTime.h"
 #include "FindOptions.h"
 #include "FrameLoaderTypes.h"
 #include "LayoutMilestones.h"
@@ -293,6 +294,9 @@ public:
     UserInterfaceLayoutDirection userInterfaceLayoutDirection() const { return m_userInterfaceLayoutDirection; }
     WEBCORE_EXPORT void setUserInterfaceLayoutDirection(UserInterfaceLayoutDirection);
 
+    void didStartProvisionalLoad();
+    void didFinishLoad(); // Called when the load has been committed in the main frame.
+
     // The view scale factor is multiplied into the page scale factor by all
     // callers of setPageScaleFactor.
     WEBCORE_EXPORT void setViewScaleFactor(float);
@@ -561,6 +565,8 @@ private:
     void checkSubframeCountConsistency() const;
 #endif
 
+    void measurePostLoadCPUUsage();
+
     enum ShouldHighlightMatches { DoNotHighlightMatches, HighlightMatches };
     enum ShouldMarkMatches { DoNotMarkMatches, MarkMatches };
 
@@ -742,6 +748,9 @@ private:
     
     // For testing.
     std::optional<EventThrottlingBehavior> m_eventThrottlingBehaviorOverride;
+
+    Timer m_cpuUsageMeasurementTimer;
+    std::optional<CPUTime> m_postLoadCPUTime;
 };
 
 inline PageGroup& Page::group()
index 6bb9d03..b4b073e 100644 (file)
@@ -778,6 +778,15 @@ bool Settings::globalConstRedeclarationShouldThrow()
 #endif
 }
 
+bool Settings::isPostLoadCPUUsageMeasurementEnabled()
+{
+#if PLATFORM(COCOA)
+    return true;
+#else
+    return false;
+#endif
+}
+
 void Settings::setAllowsAnySSLCertificate(bool allowAnySSLCertificate)
 {
     gAllowsAnySSLCertificate = allowAnySSLCertificate;
index 2c29916..a6fd1b8 100644 (file)
@@ -199,6 +199,8 @@ public:
     static bool shouldUseHighResolutionTimers() { return gShouldUseHighResolutionTimers; }
 #endif
 
+    static bool isPostLoadCPUUsageMeasurementEnabled();
+
     static bool globalConstRedeclarationShouldThrow();
 
     WEBCORE_EXPORT void setBackgroundShouldExtendBeyondPage(bool);
diff --git a/Source/WebCore/platform/CPUTime.cpp b/Source/WebCore/platform/CPUTime.cpp
new file mode 100644 (file)
index 0000000..2264409
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2017 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "CPUTime.h"
+
+namespace WebCore {
+
+#if !PLATFORM(COCOA)
+
+std::optional<CPUTime> getCPUTime()
+{
+    return std::nullopt;
+}
+
+#endif
+
+double CPUTime::percentageCPUUsageSince(const CPUTime& reference)
+{
+    int64_t cpuUsageTimeDelta = (systemTime + userTime) - (reference.systemTime + reference.userTime);
+    int64_t cpuTimeDelta = cpuTime - reference.cpuTime;
+    ASSERT(cpuTimeDelta);
+    return static_cast<double>(cpuUsageTimeDelta * 100.0) / cpuTimeDelta;
+}
+
+}
diff --git a/Source/WebCore/platform/CPUTime.h b/Source/WebCore/platform/CPUTime.h
new file mode 100644 (file)
index 0000000..d2d50be
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2017 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <wtf/Optional.h>
+
+namespace WebCore {
+
+struct CPUTime {
+    int64_t cpuTime; // in microseconds.
+    int64_t userTime; // in microseconds.
+    int64_t systemTime; // in microseconds.
+
+    double percentageCPUUsageSince(const CPUTime&);
+};
+
+std::optional<CPUTime> getCPUTime();
+
+} // namespace WebCore
diff --git a/Source/WebCore/platform/cocoa/CPUTimeCocoa.mm b/Source/WebCore/platform/cocoa/CPUTimeCocoa.mm
new file mode 100644 (file)
index 0000000..e1b1119
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2017 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "config.h"
+#import "CPUTime.h"
+
+#import <mach/mach_init.h>
+#import <mach/task.h>
+#import <mach/task_info.h>
+#import <wtf/CurrentTime.h>
+
+namespace WebCore {
+
+static const int64_t microsecondsPerSecond = 1000000;
+
+static int64_t timeValueToMicroseconds(const time_value_t& value)
+{
+    int64_t result = value.seconds;
+    result *= microsecondsPerSecond;
+    result += value.microseconds;
+    return result;
+}
+
+std::optional<CPUTime> getCPUTime()
+{
+    // Account for current threads.
+    task_thread_times_info threadInfoData;
+    mach_msg_type_number_t threadInfoCount = TASK_THREAD_TIMES_INFO_COUNT;
+    kern_return_t result = task_info(mach_task_self(), TASK_THREAD_TIMES_INFO, reinterpret_cast<task_info_t>(&threadInfoData), &threadInfoCount);
+    if (result != KERN_SUCCESS)
+        return std::nullopt;
+
+    int64_t userTime = timeValueToMicroseconds(threadInfoData.user_time);
+    int64_t systemTime = timeValueToMicroseconds(threadInfoData.system_time);
+
+    // Account for termined threads.
+    task_basic_info taskInfoData;
+    mach_msg_type_number_t taskInfoCount = TASK_BASIC_INFO_COUNT;
+    result = task_info(mach_task_self(), TASK_BASIC_INFO, reinterpret_cast<task_info_t>(&taskInfoData), &taskInfoCount);
+    if (result != KERN_SUCCESS)
+        return std::nullopt;
+
+    userTime += timeValueToMicroseconds(taskInfoData.user_time);
+    systemTime += timeValueToMicroseconds(taskInfoData.system_time);
+
+    return CPUTime { static_cast<int64_t>(monotonicallyIncreasingTime() * microsecondsPerSecond), userTime, systemTime };
+}
+
+}