Required to capture the Performance monitor details from Chrome Dev tools into Java program

kannan :

I am running a selenium test written java. As part of the test i am trying to capture/retrieve the current 'CPU Usage' and 'JS heap size' of the browser and print it in console.
Is there a way to achieve this in java code by executing a JavaScript command or something.

• CPU usage - what percentage of your CPU the site is using.
• JS heap size - how much memory (in Megabytes) is being used by the app.

I always run my test in Chrome browser. Please consider my test scenario contains a simple login for a website.

Screenshot of performance monitor

C. Peck :

As selenium can only interact with the browser itself, I don't think you can you can use it to get CPU usage from the server, and same with the JS heap size.

You could get the Java heap size created by your script; that will be available to selenium. But I don't think you can get info about server usage without some other tool or looking at the server directly.

EDIT

After a bit more thinking and searching you should be able to get your JS heap size using Selenium's JavascriptExecutor, so you should be able to get the value of window.performance.memory.usedJSHeapSize at any stage during testing. Below is the code.

  public static Double reportMemoryUsage(WebDriver webDriver, String message) {
    ((JavascriptExecutor) webDriver).executeScript("window.gc()");
    try {
        TimeUnit.SECONDS.sleep(2);
    } catch (InterruptedException e) {
        LOGGER.error(e.getLocalizedMessage());
    }
    return Double usedJSHeapSize = (Double) ((JavascriptExecutor) webDriver)
            .executeScript("return window.performance.memory.usedJSHeapSize/1024/1024");
    LOGGER.info("Memory Usage at " + usedJSHeapSize + " MB.”);
 }

If you call this method once at the beginning of your test suite and once at the end, the difference between the two usedJSHeapSize values should provide the Heap space invoked by your Selenium script.

I am forcing garbage collection before taking usedJSHeapSize, to make sure the there is no garbage information collected. To enable gc function on window, you will have to set the -js-flags=--expose-gc option.

ChromeOptions options = new ChromeOptions();
options.addArguments("-js-flags=--expose-gc");
WebDriver webDriver = new ChromeDriver(options);

Let me know if you still want to find the Java heap size from your script and I think I can come up with something for that.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=158886&siteId=1