@Override
    public void apply(final Traversal.Admin<?, ?> traversal) {
        if (!traversal.getEndStep().getLabels().contains(MARKER) &&
                (traversal.isRoot() || traversal.getParent() instanceof VertexProgramStep) &&
                TraversalHelper.hasStepOfAssignableClassRecursively(ProfileSideEffectStep.class, traversal))
            TraversalHelper.applyTraversalRecursively(t -> t.getEndStep().addLabel(MARKER), traversal);

        if (traversal.getEndStep().getLabels().contains(MARKER)) {
            traversal.getEndStep().removeLabel(MARKER);
            // Add .profile() step after every pre-existing step.
            final List<Step> steps = traversal.getSteps();
            final int numSteps = steps.size();
            for (int i = 0; i < numSteps; i++) {
                // Do not inject profiling after ProfileSideEffectStep as this will be the last step on the root traversal.
                if (steps.get(i * 2) instanceof ProfileSideEffectStep)
                    break;
                // Create and inject ProfileStep
                final ProfileStep profileStepToAdd = new ProfileStep(traversal);
                traversal.addStep((i * 2) + 1, profileStepToAdd);
            }
        }
    }
@author Bob Briody (http://bobbriody.com)
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/strategy/finalization/ProfileStrategy.java