fork(7) download
  1. import std.stdio : writeln;
  2. import std.algorithm.comparison: min;
  3. import std.algorithm.iteration: sum;
  4. import core.time: MonoTime, Duration;
  5.  
  6.  
  7. T[] sum_subranges(T)(T[] input, uint range)
  8. {
  9. T[] result = new T[(input.length + 1)/range +1];
  10. if (range == 0)
  11. {
  12. return result;
  13. }
  14. size_t it;
  15. for (uint i; i < input.length; i=min(i+range, input.length))
  16. {
  17. result[it++] = sum(input[i..min(i+range, input.length)]);
  18. }
  19. return result;
  20. }
  21.  
  22. unittest
  23. {
  24. assert(sum_subranges([1,1,1], 2) == [2, 1]);
  25. assert(sum_subranges([1,1,1,2,3,3], 2) == [2, 3, 6]);
  26. assert(sum_subranges([], 2) == []);
  27. assert(sum_subranges([1], 2) == [1]);
  28. assert(sum_subranges([1], 0) == []);
  29. }
  30.  
  31.  
  32. int main()
  33. {
  34. int[1000000] v;
  35. for (int i=0; i < 1000000; ++i)
  36. v[i] = i;
  37. int sum;
  38. MonoTime beg = MonoTime.currTime;
  39. for (int i=0; i < 100; i++)
  40. sum += cast(int)sum_subranges(v,2).length;
  41. MonoTime end = MonoTime.currTime;
  42. writeln(end-beg);
  43. writeln(sum);
  44. return sum;
  45. }
  46.  
Runtime error #stdin #stdout 1.83s 19576KB
stdin
Standard input is empty
stdout
1 sec, 832 ms, 325 μs, and 7 hnsecs
50000100