Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

66
LINES

< > BotCompany Repo | #1036379 // SingleThreadProfiler backup

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (11146L/63K).

sclass SingleThreadProfiler is AutoCloseable {
  // config
  settable Thread threadToSample = currentThread();
  settable int interval = 40; // 25 Hz
  settable bool skipSleeping;
  
  // results
  new MultiSet<S> stackTraceMultiSet;
  gettable int samples;
  
  // temporary
  java.util.Timer timer;
  Lock lock = lock();

  void start {
    lock lock;
    printWithMS("Starting profiler for " + threadToSample);
    stop();
    clear();
    timer = doEvery_daemon(interval, r {
      StackTraceElement[] stackTrace = threadToSample.getStackTrace();
      if (skipSleeping && !isThreadRunnable_x(stackTrace)) ret;
      
      lock lock;
      samples++;
      stackTraceMultiSet.add(stackTraceToString(stackTrace));
    });
  }

  public  void stop aka close() {
    lock lock;
    if (timer != null) {
      stopTimer(timer);
      timer = null;
      printWithMS("Stopped profiler for " + threadToSample);
    }
  }

  void clear() {
    lock lock;
    stackTraceMultiSet.clear();
    samples = 0;
  }

  MultiSet<S> results() {
    lock lock;
    ret cloneMultiSet(stackTraceMultiSet);
  }

  MultiSet<S> stopAndGetResults() {
    lock lock;
    stop();
    ret results();
  }
  
  S renderFullResults(bool mostImportantLast) {
    var traces = results();
    int n = traces.size();
    int percent = ratioToIntPercent(l(traces), samples);
    ret (samples == 0 ? "Nothing sampled"
      : percent + "% core activity [" + n2(samples, "sample") + " taken]") + "\n\n"
      + joinMap(mostImportantLast ? traces.lowestFirst() : traces.highestFirst(), trace ->
      traces.get(trace) + "/" + n + "\n" + trace + "\n\n"
    );
  }
}

Author comment

Began life as a copy of #1035050

download  show line numbers  debug dex  old transpilations   

Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj

No comments. add comment

-
Snippet ID: #1036379
Snippet name: SingleThreadProfiler backup
Eternal ID of this version: #1036379/1
Text MD5: 30e2a0a81b8dbf7996314f1fed6d6e91
Transpilation MD5: 358b0e3c8f947590156274908926d18c
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-11-30 11:50:40
Source code size: 1697 bytes / 66 lines
Pitched / IR pitched: No / No
Views / Downloads: 122 / 172
Referenced in: