ndslice, using a slice in place of T[] in template parameters
Jay Norwood via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jan 10 14:00:20 PST 2016
I cut this median template from Jack Stouffer's article and was
attempting to use it in a parallel function. As shown, it
builds and execute correctly, but it failed to compile if I
attempting to use
medians[i] = median(vec,slb[task]);
in place of the
medians[i] = median(vec,dbuf[j .. k]);
Is there a cast needed?
================
import std.array : array;
import std.algorithm;
import std.datetime;
import std.conv : to;
import std.stdio;
import std.experimental.ndslice;
shared double[] medians;
double[] data;
shared double[] dbuf;
int numTasks;
const int smalld = 1000;
const int bigd = 10_000;
const int fulld = bigd*smalld;
/**
Params:
r = input range
buf = buffer with length no less than the number of elements in
`r`
Returns:
median value over the range `r`
*/
T median(Range, T)(Range r, T[] buf)
{
import std.algorithm.sorting: sort;
size_t n;
foreach (e; r) {
buf[n++] = e;
}
buf[0 .. n].sort();
immutable m = n >> 1;
return n & 1 ? buf[m] : cast(T)((buf[m - 1] + buf[m]) / 2);
}
void f3() {
import std.parallelism;
auto sl = data.sliced(smalld,bigd);
auto slb = dbuf.sliced(numTasks,bigd);
foreach(i,vec; parallel(sl)){
int task = taskPool.workerIndex;
int j = task*bigd;
int k = j+bigd;
medians[i] = median(vec,dbuf[j .. k]);
}
}
void main() {
import std.parallelism;
numTasks = taskPool.size+1;
data = new double[fulld];
dbuf = new double[bigd*numTasks];
medians = new double[smalld];
for(int i=0;i<fulld;i++){ data[i] = i/(fulld*1.0);}
StopWatch sw3;
sw3.start();
f3() ;
auto r3 = sw3.peek().msecs;
writeln("medians parallel:",medians);
writeln("parallel time medians msec:",r3);
}
More information about the Digitalmars-d-learn
mailing list