Advertisement
Guest User

Untitled

a guest
Apr 26th, 2018
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. package eu.ase.hpc.multith.paralel;
  2.  
  3. public class ProgMainParalel {
  4. private static final int NTHREADS=4;
  5. public static void main(String[] args) {
  6. int dimVect=40_000_000;
  7. int[] v = new int[dimVect];
  8. for(int i=0;i<dimVect;i++)
  9. v[i]=1+i;
  10.  
  11.  
  12.  
  13. int startIdx =0, stopIdx=0;
  14. long startTime =0, stopTime=0;
  15. Long[] vectSum =new Long[NTHREADS];
  16.  
  17.  
  18. //1. seq
  19. Long sum = new Long(0);
  20. startTime=System.currentTimeMillis();
  21. for(int i=0;i<dimVect; i++) {
  22. sum+=v[i];
  23. }
  24. stopTime=System.currentTimeMillis();
  25. System.out.println("1. Seq time = "+ (stopTime-startTime)+ ", sum = " +sum);
  26.  
  27.  
  28. //2. standart multi threading
  29.  
  30. sum = new Long(0);
  31. startTime=System.currentTimeMillis();
  32.  
  33. Thread[] vectThreads = new Thread[NTHREADS];
  34. MyMultiThArray[] vectRThreads= new MyMultiThArray[NTHREADS];
  35.  
  36. for(int it=0; it<NTHREADS; it++) {
  37. startIdx = it* (dimVect/NTHREADS);
  38. stopIdx=(it+1)* (dimVect/NTHREADS)-1;
  39. vectSum[it]= new Long(0);
  40. vectRThreads[it]= new MyMultiThArray(v, startIdx, stopIdx);
  41. vectThreads[it]= new Thread(vectRThreads[it]);
  42. }
  43.  
  44. for(int it=0;it<NTHREADS;it++) {
  45. vectThreads[it].start();
  46. }
  47.  
  48. for(int it=0;it<NTHREADS;it++) {
  49. try {
  50. vectThreads[it].join();
  51. }catch(InterruptedException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55.  
  56. for(int it=0;it<NTHREADS;it++) {
  57. vectSum[it]=vectRThreads[it].getSum();
  58. sum+= vectSum[it];
  59. }
  60.  
  61. stopTime=System.currentTimeMillis();
  62. System.out.println("2. Multi threading time = "+ (stopTime-startTime)+ ", sum = " +sum);
  63.  
  64. }
  65. }
  66.  
  67.  
  68.  
  69.  
  70. package eu.ase.hpc.multith.paralel;
  71.  
  72. public class MyMultiThArray implements Runnable {
  73. private int[] vinp;
  74. private int start;
  75. private int stop;
  76. private Long sum;
  77.  
  78.  
  79. public MyMultiThArray(int[] v, int startIdx, int stopIdx) {
  80. this.vinp=v;
  81. this.start= startIdx;
  82. this.stop=stopIdx;
  83.  
  84. }
  85.  
  86. @Override
  87. public void run() {
  88. long s=0;
  89. for(int idx=this.start;idx<=this.stop;idx++) {
  90. s+= this.vinp[idx];
  91. }
  92. this.sum=new Long(s);
  93. }
  94.  
  95. public Long getSum() {
  96. return this.sum;
  97. }
  98.  
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement