Advertisement
Sinux1

atomic

Nov 13th, 2019
1,952
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.86 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <ctype.h>
  3. #include <string.h>
  4. #include <omp.h>
  5. int main()
  6. {
  7.     //starting time for calculating run time
  8.     double start = omp_get_wtime( );
  9.     //enum for purposes of declaring array size with variable
  10.     enum SIZE {SIZE = 26};
  11.  
  12.     //array to hold number of occurences of each letter in alphabet
  13.     //with index 0 representing A,..., index 25 = Z
  14.     int s_res[SIZE] = {};
  15.  
  16.     //number of threads requested
  17.     const int NUMB = 10;
  18.  
  19.     //char string for identifying chars from txt
  20.     char * alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  21.  
  22.     //requessting that num threads is num of books
  23.     omp_set_num_threads(NUMB);
  24.  
  25.     //omp parralel and for, using static, 1 because best time results for me
  26.     #pragma omp parallel for schedule(static,1)
  27.        for(int i=0;i<NUMB;i++)
  28.        {
  29.             //adding ID to char '0' will result in char '0' - '9' depending on ID
  30.             char filename[] = {'0' + i,'.','t','x','t'};
  31.            
  32.             FILE *fptr;
  33.             fptr=fopen(filename,"r");
  34.             char ch;
  35.             //loop through txt file char at a time
  36.             while((ch=toupper((fgetc(fptr))))!=EOF)
  37.             {
  38.                 //pointer to memory address of ch in alpha
  39.                 const char *ptr = strchr(alpha, ch);
  40.                 if(ptr!=NULL)
  41.                 {  
  42.                     //calculate correct index
  43.                     int index = ptr - alpha;
  44.                     #pragma omp atomic
  45.                     //use index to increment array
  46.                     s_res[index]++;
  47.                 }
  48.  
  49.             }
  50.         }
  51.  
  52.     //ending time for calculating run time
  53.     double end = omp_get_wtime( );
  54.  
  55.     printf("\nCompleted in %f seconds", end-start);
  56.     printf("\nThe letter frequencies are:\n");
  57.     //print results
  58.     for (int i =0; i < 26; i++)
  59.     {
  60.         printf("%c's: %d\n", alpha[i], s_res[i] );
  61.     }
  62.  
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement