|
| 1 | +function a = parfor_example |
| 2 | +% This example creates a trace through a parfor loop, by creating a span in |
| 3 | +% each iteration and propagating context. |
| 4 | +% |
| 5 | +% Copyright 2024 The MathWorks, Inc. |
| 6 | + |
| 7 | +% initialize tracing |
| 8 | +runOnce(@initTracer); |
| 9 | + |
| 10 | +% start the top level span and make it current |
| 11 | +tr = opentelemetry.trace.getTracer("parfor_example"); |
| 12 | +sp = startSpan(tr, "main function"); |
| 13 | +scope = makeCurrent(sp); %#ok<*NASGU> |
| 14 | + |
| 15 | +n = 80; |
| 16 | +A = 500; |
| 17 | +a = zeros(1,n); % initialize the output |
| 18 | +nworkers = 4; % maximum number of workers |
| 19 | + |
| 20 | +% propagate the current context by extracting and passing it in headers |
| 21 | +carrier = opentelemetry.context.propagation.injectContext(); |
| 22 | +headers = carrier.Headers; |
| 23 | + |
| 24 | +parfor (i = 1:n, nworkers) |
| 25 | + % parfor block needs its own initialization |
| 26 | + runOnce(@initTracer); |
| 27 | + |
| 28 | + % extract context from headers and make it current |
| 29 | + carrier = opentelemetry.context.propagation.TextMapCarrier(headers); |
| 30 | + newcontext = opentelemetry.context.propagation.extractContext(carrier); |
| 31 | + scope_i = setCurrentContext(newcontext); |
| 32 | + |
| 33 | + % start a span for this iteration |
| 34 | + tr_i = opentelemetry.trace.getTracer("parfor_example"); |
| 35 | + sp_i = startSpan(tr_i, "Iteration" + i); |
| 36 | + |
| 37 | + % compute the maximum eigenvalue of a random matrix |
| 38 | + a(i) = max(abs(eig(rand(A)))); |
| 39 | + |
| 40 | + % end the scope and the span |
| 41 | + scope_i = []; |
| 42 | + endSpan(sp_i); |
| 43 | +end |
| 44 | +end |
| 45 | + |
| 46 | +function initTracer |
| 47 | +% set up global TracerProvider |
| 48 | +resource = dictionary("service.name", "OpenTelemetry-Matlab_examples"); |
| 49 | +tp = opentelemetry.sdk.trace.TracerProvider(... |
| 50 | + opentelemetry.sdk.trace.SimpleSpanProcessor, Resource=resource); |
| 51 | +setTracerProvider(tp); |
| 52 | + |
| 53 | +% set up global propagator |
| 54 | +prop = opentelemetry.trace.propagation.TraceContextPropagator(); |
| 55 | +setTextMapPropagator(prop); |
| 56 | +end |
| 57 | + |
| 58 | +% This helper ensures the input function is only run once |
| 59 | +function runOnce(fh) |
| 60 | +persistent hasrun |
| 61 | +if isempty(hasrun) |
| 62 | + feval(fh); |
| 63 | + hasrun = 1; |
| 64 | +end |
| 65 | +end |
0 commit comments