Question

In: Computer Science

File input.txt contains 100,000 numbers separated by new line. Do the following: Write a C++ program...

  1. File input.txt contains 100,000 numbers separated by new line. Do the following:
    1. Write a C++ program to compute the summation of these 100,000 numbers using single thread.
    2. Write a C++ program to compute the summation of these 100,000 numbers using 10 threads, meaning each thread compute 10,000 summations and the main thread sum the result of the 10 threads.
    3. Using the time syscall to compare the time spent for 1.1 and 1.2

Turn Ins:

Source code of two programs and a short report on to answer the following question:

  1. What is the run time for 1.1?
  2. What is the run time for 1.2?
  3. Is there a run time difference and why?

input.txt looks like below

55
59
56
23
93
9
39
76
27
81
46
99
35
11
93
43
10
22
29
89
8
10
11
86
48
34
39
3
54
4
76
2
35
52
58
92
75
15
48
51
29
81
96
25
46
90
67
40
55
67
44
76
3
48
31
61
48
9
64
68
78
4
17
26
63
64
92
11
58
54
71
51
11
16
27
76
91
8
77
35
12
84
87
93
71
14
5
36
16
35
30
47
85
81
78
34

Solutions

Expert Solution

Here is the solution -

I have used a input.txt file that has almost 20,000 integers, for testing purpose.

Code for both parts of question are exactly same, just change the " #define MAX_THREAD <value>"

to have that many threads in program. Here is the code for both cases:

CASE 1 : Single Thread Program

Time taken : 85890 microseconds (see output image)

#include <bits/stdc++.h> 
#include <chrono> 
#include <fstream>
#include <iostream> 
#include <pthread.h> 
  
// size of array 
#define MAX 100000
  
// maximum number of threads 
#define MAX_THREAD 1

//chrono is used for record the time in execution
using namespace std::chrono;  
using namespace std; 

//global variables  a[]=array of long integers, sum[] = array of threads   
long long a[MAX];
long long sum[MAX_THREAD] = { 0 }; 
int part = 0; //current thread(part)


//function to sum the values of thread's part  
void* sum_array(void* arg) 
{   
    // Each thread computes sum of 1/nth of array 
    long long thread_part = part++; 
    for (int i = thread_part * (MAX / MAX_THREAD); i < (thread_part + 1) * (MAX / MAX_THREAD); i++) 
        sum[thread_part] += a[i]; 
} 


// Driver Code 
int main() 
{   
    // Get starting timepoint 
    auto start = high_resolution_clock::now(); 
    
    
    //reading file and populating array
    fstream file;
        int x;
        file.open("input.txt");
    int count = 0;
        while(file>>x){
            a[count] = x;
            count++;
                }
        file.close();

    //initialize the array of threads
    pthread_t threads[MAX_THREAD]; 
    
    
    // Creating 10 threads 
    for (int i = 0; i < MAX_THREAD; i++) 
        pthread_create(&threads[i], NULL, sum_array, (void*)NULL); 
  
    // joining 10 threads i.e. waiting for all 4 threads to complete 
    for (int i = 0; i < MAX_THREAD; i++) 
        pthread_join(threads[i], NULL); 
  
    // adding sum of all parts  (10 if using 10 threads, 1 if using 1 thread)
    int total_sum = 0; 
    for (int i = 0; i <MAX_THREAD; i++) 
        total_sum += sum[i]; 
  
    cout << "sum is " << total_sum << endl; 
        
    // Get ending timepoint 
    auto stop = high_resolution_clock::now(); 
  
  
    // Get duration. Substart timepoints to  
    // get durarion. To cast it to proper unit 
    // use duration cast method 
    auto duration = duration_cast<microseconds>(stop - start); 
  
    cout << "Time taken by program: "
         << duration.count() << " microseconds" << endl; 
  
    return 0; 
} 

OUTPUT:

CASE 2: 10 Threads Program

Time taken : 8145 microseconds (see output image)

#include <bits/stdc++.h> 
#include <chrono> 
#include <fstream>
#include <iostream> 
#include <pthread.h> 
  
// size of array 
#define MAX 100000
  
// maximum number of threads 
#define MAX_THREAD 10

//chrono is used for record the time in execution
using namespace std::chrono;  
using namespace std; 

//global variables  a[]=array of long integers, sum[] = array of threads   
long long a[MAX];
long long sum[MAX_THREAD] = { 0 }; 
int part = 0; //current thread(part)


//function to sum the values of thread's part  
void* sum_array(void* arg) 
{   
    // Each thread computes sum of 1/nth of array 
    long long thread_part = part++; 
    for (int i = thread_part * (MAX / MAX_THREAD); i < (thread_part + 1) * (MAX / MAX_THREAD); i++) 
        sum[thread_part] += a[i]; 
} 


// Driver Code 
int main() 
{   
    // Get starting timepoint 
    auto start = high_resolution_clock::now(); 
    
    
    //reading file and populating array
    fstream file;
        int x;
        file.open("input.txt");
    int count = 0;
        while(file>>x){
            a[count] = x;
            count++;
                }
        file.close();

    //initialize the array of threads
    pthread_t threads[MAX_THREAD]; 
    
    
    // Creating 10 threads 
    for (int i = 0; i < MAX_THREAD; i++) 
        pthread_create(&threads[i], NULL, sum_array, (void*)NULL); 
  
    // joining 10 threads i.e. waiting for all 4 threads to complete 
    for (int i = 0; i < MAX_THREAD; i++) 
        pthread_join(threads[i], NULL); 
  
    // adding sum of all parts  (10 if using 10 threads, 1 if using 1 thread)
    int total_sum = 0; 
    for (int i = 0; i <MAX_THREAD; i++) 
        total_sum += sum[i]; 
  
    cout << "sum is " << total_sum << endl; 
        
    // Get ending timepoint 
    auto stop = high_resolution_clock::now(); 
  
  
    // Get duration. Substart timepoints to  
    // get durarion. To cast it to proper unit 
    // use duration cast method 
    auto duration = duration_cast<microseconds>(stop - start); 
  
    cout << "Time taken by program: "
         << duration.count() << " microseconds" << endl; 
  
    return 0; 
} 

Questions:

  1. What is the run time for 1.1?
  2. What is the run time for 1.2?
  3. Is there a run time difference and why?

Answers:

1. 85890 microsecond

2. 8145 microsecond

3. Hence with above observations, it is clear that multithreaded program( 10 threads) takes very less time than the single threaded program. While a thread is waiting for hardware to response the CPU switches to another thread that is not waiting for hardware to response. ... When two CPU are available both calculations can be done at the same time thus speeding up your program.


Related Solutions

Write a C++ programm which reads an input file named 'input.txt' content of input.txt are not...
Write a C++ programm which reads an input file named 'input.txt' content of input.txt are not known to you copies content of input file into an output file named 'output.txt' contents of output.txt should be exactly the same as contents of input.txt the user should be given a choice to select input and output file in any folder remember to check that input file opened successfully Please add comments next to the code, so I can learn from the solution....
Write a C++ pgm which 1.reads an input file named 'input.txt' 2.content of input.txt are not...
Write a C++ pgm which 1.reads an input file named 'input.txt' 2.content of input.txt are not known to you 3.copies content of input file into an output file named 'output.txt' 4.contents of output.txt should be exactly the same as contents of input.txt 5.the user should be given a choice to select input and output file in any folder 6.remember to check that input file opened successfully
A hotel salesperson enters sales in a text file. Each line contains the following, separated by...
A hotel salesperson enters sales in a text file. Each line contains the following, separated by semicolons: The name of the client, the service sold (such as Dinner, Conference, Lodging, and so on), the amount of the sale, and the date of that event. Write a program that reads such a file and displays the total amount for each service category. Use the following data for your text file:5 pts Bob;Dinner;10.00;January 1, 2013 Tom;Dinner;14.00;January 2, 2013 Anne;Lodging;125.00;January 3, 2013 Jerry;Lodging;125.00;January...
Write a Python program called “exam.py”. The input file, “input.txt”, is given to you in the...
Write a Python program called “exam.py”. The input file, “input.txt”, is given to you in the Canvas exam instructions. Name your output file “output.txt”. Ensure the program consists of a main function and at least one other function. Ensure the program will read the input file, and will output the following information to the output file as well as printing it to the screen: output the text of the file to screen output the number of words in the file...
how to creat Create a text file that contains a list of integer numbers separated by...
how to creat Create a text file that contains a list of integer numbers separated by comma (numbers.txt). E.g. 3, 7, 5, 1, 11, 8,2, 6 2- how to Write a python program (minMax.py) to read the file numbers.txt and find the largest and smallest numbers in the file. (without using use min(), max()). calculate the average and output the results. 3-Use python file i/o, write a python program (fileCopy.py) that makes a copy of minMax.py (Read contents of minMax.cp...
Write a program that reads from the external file input.txt, capitalizes all words that begin with...
Write a program that reads from the external file input.txt, capitalizes all words that begin with the letter "a," and then writes them to an external file output.txt (Note: Do not forget to copy the blanks. You may wish to use infile.get and outfile.put in your program.) Output: After the program generates output.txt, the code should display the contents of the file on the screen to verification.
Write a program in Java that reads an input text file (named: input.txt) that has several...
Write a program in Java that reads an input text file (named: input.txt) that has several lines of text and put those line in a data structure, make all lowercase letters to uppercase and all uppercase letters to lowercase and writes the new lines to a file (named: output.txt).
C++ Write a program that reads candidate names and numbers of votes in from a file....
C++ Write a program that reads candidate names and numbers of votes in from a file. You may assume that each candidate has a single word first name and a single word last name (although you do not have to make this assumption). Your program should read the candidates and the number of votes received into one or more dynamically allocated arrays. In order to allocate the arrays you will need to know the number of records in the file....
How do I do this: Write a program that can read a text file of numbers...
How do I do this: Write a program that can read a text file of numbers and calculate the mean and standard deviation of those numbers. Print the result in another text file. Put the result on the computer screen. EACH LINE OF THE PROGRAM MUST BE COMMENTED!
Write a program in c that reads the content from the file and stores each line...
Write a program in c that reads the content from the file and stores each line in an int array in heap(using dynamic memory allocation). For example, let the file has elements following (we do not know the size of files, it could be above 100,000 and contents of the file and make sure to convert file elements to int): 10067 26789 6789 3467
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT