Elapsed time for a single event only, i.e. since the previous stage rather than from the start, summed over all executions,
for the last thread that executed this KernelDeviceProfile instance respective kernel and device.

@param stage the event stage
165580
public double getCumulativeElapsedTimeGlobal(ProfilingEvent stage) {
	   final long[] accumulatedTimesHolder = new long[NUM_EVENTS];
	   globalAcc.consultAccumulatedTimes(accumulatedTimesHolder);

	   return accumulatedTimesHolder[stage.ordinal()] / MILLION;
   }
65686
public Long getDurationOfLastSuccessfulOnAgent(String pipelineName, String stageName, JobInstance job) {
        String key = job.getBuildDurationKey(pipelineName, stageName);
        Long duration;
        try {
            duration = (Long) cache.getFromCache(key, CacheEntry.INDEFINITE_EXPIRY);
        } catch (NeedsRefreshException nre) {
            boolean updated = false;
            try {
                duration = recalculateBuildDuration(pipelineName, stageName, job);
                cache.putInCache(key, duration);
                updated = true;
            } finally {
                if (!updated) {
                    // It is essential that cancelUpdate is called if the
                    // cached content could not be rebuilt
                    cache.cancelUpdate(key);
                    LOGGER.warn("refresh cancelled for {}", key);
                }
            }
        }
        return duration;
    }
1182246
public void setStageKeys(java.util.Collection<String> stageKeys) {
        if (stageKeys == null) {
            this.stageKeys = null;
            return;
        }

        this.stageKeys = new java.util.ArrayList<String>(stageKeys);
    }
1145912
function() {
    // Set `eventQueue` to null before processing it so that we can tell if more
    // events get enqueued while processing.
    var processingEventQueue = eventQueue;
    eventQueue = null;
    forEachAccumulated(processingEventQueue, executeDispatchesAndRelease);
    ("production" !== "development" ? invariant(
      !eventQueue,
      'processEventQueue(): Additional events were enqueued while processing ' +
      'an event queue. Support for this has not yet been implemented.'
    ) : invariant(!eventQueue));
  }
792654
private List<SimulatorEvent> processTaskAttemptCompletionEvent(
      TaskAttemptCompletionEvent event) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Processing task attempt completion event" + event);
    }
    
    long now = event.getTimeStamp();  
    TaskStatus finalStatus = event.getStatus();
    TaskAttemptID taskID = finalStatus.getTaskID();
    boolean killedEarlier = orphanTaskCompletions.remove(taskID);
    if (!killedEarlier) {
      finishRunningTask(finalStatus, now);
    }
    return SimulatorEngine.EMPTY_EVENTS;
  }
721644
public void runtimeEventOccurred(RuntimeEvent event)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) 
      SibTr.debug(tc, "runtimeEventOccurred", event);
  }
1309577
private void collectStartVertices(final ManagementStage stage) {

		for (int i = 0; i < stage.getNumberOfGroupVertices(); i++) {

			final ManagementGroupVertex groupVertex = stage.getGroupVertex(i);

			if (this.forward) {
				if ((groupVertex.getNumberOfBackwardEdges() == 0)
					|| ((this.stage >= 0) && allConnectionsFromOtherStage(groupVertex, true))) {
					this.entryVertices.add(groupVertex);
				}
			} else {
				if ((groupVertex.getNumberOfForwardEdges() == 0)
					|| ((this.stage >= 0) && allConnectionsFromOtherStage(groupVertex, false))) {
					this.entryVertices.add(groupVertex);
				}
			}
		}
	}
149222
@Override
    public void addAction(final LifecycleStage stage, final LifecycleAction<T> action)
    {
        stageEvents.add(new StageEvent(stage, action));
    }
171805
public void reportDeviceUsage(StringBuilder builder, boolean withProfilingInfo) {
      builder.append("Device Usage by Kernel Subclass");
      if (withProfilingInfo) {
         builder.append(" (showing mean elapsed times in milliseconds)");
      }
      builder.append("\n\n");
      for (PreferencesWrapper wrapper : preferences.values()) {
         KernelPreferences preferences = wrapper.getPreferences();
         Class<? extends Kernel> klass = wrapper.getKernelClass();
         KernelProfile profile = withProfilingInfo ? profiles.get(klass) : null;
         builder.append(klass.getName()).append(":\n\tusing ").append(preferences.getPreferredDevice(null).getShortDescription());
         List<Device> failedDevices = preferences.getFailedDevices();
         if (failedDevices.size() > 0) {
            builder.append(", failed devices = ");
            for (int i = 0; i < failedDevices.size(); ++i) {
               builder.append(failedDevices.get(i).getShortDescription());
               if (i < failedDevices.size() - 1) {
                  builder.append(" | ");
               }
            }
         }
         if (profile != null) {
            builder.append("\n");
            int row = 0;
            for (KernelDeviceProfile deviceProfile : profile.getDeviceProfiles()) {
               if (row == 0) {
                  builder.append(deviceProfile.getTableHeader()).append("\n");
               }
               builder.append(deviceProfile.getAverageAsTableRow()).append("\n");
               ++row;
            }
         }
         builder.append("\n");
      }
   }
123177
public static Throwable getFailed(CompletionStage<?> stage) {
    CompletableFuture<?> future = stage.toCompletableFuture();
    Preconditions.checkArgument(future.isCompletedExceptionally());
    try {
      future.get();
      throw new AssertionError("future should be failed");
    } catch (InterruptedException e) {
      throw new AssertionError("Unexpected error", e);
    } catch (ExecutionException e) {
      return e.getCause();
    }
  }
1203439
@Override
    public void synchronizeThreadDevice(Long threadId, Integer deviceId, AllocationPoint point) {
        // we synchronize only if this AllocationPoint was used within device context, so for multiple consequent syncs only first one will be issued
        flowController.synchronizeToHost(point);
    }
1102031
private synchronized void recordElapsedTime() {
        // do nothing if the timer is not started
        if (startTime == 0)
            return;
        long current = System.nanoTime();
        // It is reported that elapsed time can be negative on some platforms.
        // Use the absolute difference to avoid infinite waits.
        timeWaited += Math.abs(current - startTime);
        // continue timing from now
        startTime = current;
    }
205062
public Stage cancelAndTriggerRelevantStages(Long stageId, Username username, LocalizedOperationResult result) throws Exception {
        Stage stageForId;
        LocalizedOperationResult opResult = result == null ? new DefaultLocalizedOperationResult() : result;
        try {
            stageForId = stageService.stageById(stageId);
        } catch (Exception e) {
            LOGGER.error("[Stage Cancellation] Failed to retrieve stage identifier", e);
            opResult.notFound("Stage '" + stageId + "' not found.", HealthStateType.general(HealthStateScope.GLOBAL));
            return null;
        }

        if (!stageForId.isActive()) {
            opResult.setMessage("Stage is not active. Cancellation Ignored.");
            return stageForId;
        }

        String stageMutex = mutexForStageInstance(stageForId.getIdentifier());
        synchronized (stageMutex) {
            // reload stage so we see committed state after acquiring mutex
            final Stage stage = stageService.stageById(stageId);

            String pipelineName = stage.getIdentifier().getPipelineName();
            String stageName = stage.getIdentifier().getStageName();
            String user = username == null ? null : username.getUsername().toString();

            if (!securityService.hasOperatePermissionForStage(pipelineName, stageName, user)) {
                opResult.forbidden("Unauthorized to operate stage named " + stageName, HealthStateType.forbidden());
                return null;
            }

            LOGGER.info("[Stage Cancellation] Cancelling stage {}", stage.getIdentifier());
            transactionTemplate.executeWithExceptionHandling(new com.thoughtworks.go.server.transaction.TransactionCallbackWithoutResult() {
                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) {
                    stageService.cancelStage(stage, user);
                }
            });

            transactionTemplate.executeWithExceptionHandling(new com.thoughtworks.go.server.transaction.TransactionCallbackWithoutResult() {
                @Override
                public void doInTransactionWithoutResult(TransactionStatus status) throws Exception {
                    automaticallyTriggerRelevantStagesFollowingCompletionOf(stage);
                }
            });

            opResult.setMessage("Stage cancelled successfully.");

            return stage;
        }
    }
767454
public void event(Kernel kernel, Event event)
   {
      if (event == Event.PRE_CLASSLOADER)
      {
         SecurityActions.setSystemProperty("xb.builder.useUnorderedSequence", "true");
         SecurityActions.setSystemProperty("java.util.logging.manager", "org.jboss.logmanager.LogManager");
         SecurityActions.setSystemProperty("log4j.defaultInitOverride", "true");
      }
   }
8677
def _run_events(self, tag, stage=None):
        """"""

        self._run_event_methods(tag, stage)
        self._run_tests(tag, stage)
1247730
public void setStageKeys(java.util.Collection<StageKey> stageKeys) {
        if (stageKeys == null) {
            this.stageKeys = null;
            return;
        }

        this.stageKeys = new java.util.ArrayList<StageKey>(stageKeys);
    }
919531
public void reload(Long processId) {
        try {
            if (logger.isDebugEnabled()) {
                logger.debug("## reload Stage pipeline[{}] process[{}]", getPipelineId(), processId);
            }

            initProcessStage(processId);
        } catch (Exception cause) {
        }
    }