Link to home
Create AccountLog in
Avatar of mjs2011
mjs2011Flag for Saudi Arabia

asked on

I need to print execution time by using openmp (omp_get_wtime)

I need to print execution time by using openmp (omp_get_wtime)


#include <limits.h>
#include <iostream>
#include <numeric>
#include <fstream>
#include <vector>
#include <string.h>
#include <iomanip>
#include <omp.h>
#include <time.h>
using namespace std;
int main()
{
    double start = omp_get_wtime();
    vector<string> codons = { "ttt" }; // Better always initialize any variable or array or objects to zero or NULL or empty string.
    codons.push_back("ttc"); // { "ttt", "ttc"
    codons.push_back("tta"); // { "ttt", "ttc", "tta"
    codons.push_back("ttg"); // { "ttt", "ttc", "tta", ...
    codons.push_back("tct");
    codons.push_back("tcc");
    codons.push_back("tca");
    codons.push_back("tcg");
    codons.push_back("tat");
    codons.push_back("tac");
    codons.push_back("taa");
    codons.push_back("tag");
    codons.push_back("tgt");
    codons.push_back("tgc");
    codons.push_back("tga");
    codons.push_back("tgg");
    codons.push_back("ctt");
    codons.push_back("ctc");
    codons.push_back("cta");
    codons.push_back("ctg");
    codons.push_back("cct");
    codons.push_back("ccc");
    codons.push_back("cca");
    codons.push_back("ccg");
    codons.push_back("cat");
    codons.push_back("cac");
    codons.push_back("caa");
    codons.push_back("cag");
    codons.push_back("cgt");
    codons.push_back("cgc");
    codons.push_back("cga");
    codons.push_back("cgg");
    codons.push_back("att");
    codons.push_back("atc");
    codons.push_back("ata");
    codons.push_back("atg");
    codons.push_back("act");
    codons.push_back("acc");
    codons.push_back("aca");
    codons.push_back("acg");
    codons.push_back("aat");
    codons.push_back("aac");
    codons.push_back("aaa");
    codons.push_back("aag");
    codons.push_back("agt");
    codons.push_back("agc");
    codons.push_back("aga");
    codons.push_back("aag");
    codons.push_back("gtt");
    codons.push_back("gtc");
    codons.push_back("gta");
    codons.push_back("gtg");
    codons.push_back("gct");
    codons.push_back("gcc");
    codons.push_back("gca");
    codons.push_back("gcg");
    codons.push_back("gat");
    codons.push_back("gac");
    codons.push_back("gaa");
    codons.push_back("gag");
    codons.push_back("ggt");
    codons.push_back("ggc");
    codons.push_back("gga");
    codons.push_back("ggg"); // // { "ttt", "ttc", "tta", ..., "ggg"}
    // codons.size() is 64
    vector<int> counts(64, 0);
    string line = ""; // Always initialize.
    // int numberOfLines=0; // warning: unused variable numberOfLines
    string FileContent = "";
    string curLine = "";
    // No need to open the file inside a loop
    ifstream myfile("mouse.dat");
    if (myfile.is_open())
    {
        while (!myfile.eof())
        {
            curLine = ""; // Added this line after finding following exception when searching words "tct" "ctc"
            /*
            ------------- Exception result 4991 ------------------
            tct 4991
            Actual count: 4990
            ------------- Exception result 4687 ------------------
            ctc 4687
            Actual count: 4686
            */
            myfile >> curLine;
            FileContent += curLine;
            if ("" == curLine) // Remove blank lines if present
            {
                continue;
            }
        }
        myfile.close();
    }
    else
    {
        cout << "Unable to open file ";
        perror("Error: ");
        exit(1);
    }
    omp_set_num_threads(16);
    int id;
    id = omp_get_thread_num();
#pragma omp parallel private(id)
    {
#pragma omp sections 
        {
#pragma omp section 
            {
                for (int indx = 0; 64 > indx; indx++) // Better compare using "number comparison variable" way
                {
                    ifstream myfile("mouse.dat");
                    // Use this line for debugging
                    // cout << "FileContent:" << FileContent << '\n';
                    unsigned long CodonsLoc = 0;
                    if ("tct" == codons[indx])
                    {
                        // cout << "debuging\n";
                    }
                    while (ULONG_MAX != (CodonsLoc = FileContent.find(codons[indx], CodonsLoc)))
                    {
                        counts[indx]++;
                        // cout << "counts[indx] " << counts[indx] << '\n';
                        CodonsLoc += codons[indx].length();
                    }
                }
            
                ofstream newFile("results.txt");
                if (newFile.fail())
                {
                    perror("Opening results.txt file failed");
                    exit(2);
                }
                else
                {
                    unsigned int TotalCount = accumulate(counts.begin(), counts.end(), 0);
                    cout << "TotalCount: " << TotalCount << '\n';
                    newFile << "TotalCount: " << TotalCount << '\n';
                    for (int indx = 0; 64 > indx; indx++) // Better compare using "number comparison variable" way
                    {
                        // using setprecision having 9 digits at float
                        // using fixed to keep trailing zeros.
                        // Using setw(4) for counts[indx] alignment
                        cout << codons[indx] << " " << setw(4) << counts[indx] << " percent: " << fixed << setprecision(9) << (float)100 * counts[indx] / TotalCount << '\n';
                        newFile << codons[indx] << " " << setw(4) << counts[indx] << " percent: " << fixed << setprecision(9) << (float)100 * counts[indx] / TotalCount << '\n';
                    }
                    newFile.close();
                }
            }
        }
    }
    return 0;
    printf("Time: \t %f \n", omp_get_wtime() - start);

}

Open in new window

Avatar of MURUGESAN N
MURUGESAN N
Flag of India image

@mjs2011
a)

Replace:
        }
        return 0;
        printf("Time: \t %f \n", omp_get_wtime() - start);
}
With:
        }
        printf("Time: \t %f \n", omp_get_wtime() - start);
        return 0;
}

and recompile to get the Time.

b)
// Always initialize a variable.
int id = 0;
SOLUTION
Avatar of MURUGESAN N
MURUGESAN N
Flag of India image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of mjs2011

ASKER

thanks a lot
$ echo MOST wELcOME | /usr/bin/wc >/dev/null
Avatar of sarabande
	for (int indx = 0; 64 > indx; indx++) // Better compare using "number comparison variable" way
		{
			ifstream myfile("mouse.dat");
			// Use this line for debugging
			// cout << "FileContent:" << FileContent << '\n';
			unsigned long CodonsLoc = 0;
			if ("tct" == codons[indx])
			{
				// cout << "debuging\n";
			}
			while (ULONG_MAX != (CodonsLoc = FileContent.find(codons[indx], CodonsLoc)))
			{
				counts[indx]++;
				// cout << "counts[indx] " << counts[indx] << '\n';
				CodonsLoc += codons[indx].length();
			}
		}

Open in new window


msj2011,

The coding part where the occurences of the codons are counted is still wrong and extremely inefficient.

  • Remove statement 'ifstream myFile("mouse.dat");' because myFile was not used in the loop.
  • Don't use a for loop from 0 to 64 to look for the occurrences of each of the 64 codes because one single loop is sufficient (see below).
  • Don't use FileContents.find(codon). the find function will find occurences which are not valid because the position in the contents is not a multiple of 3.  

Counting can be done with one loop:

    std::map<std::string, int> countMap;
    std::string codon(3, '\0');
    len = FileContents.length();
    for (int i = 0; i < len-2; i += 3)
    {
          codon = FileContents.substr(i, 3);
          countMap[codon]++;
    }

Open in new window


this code relies on a proper input. e. g. the file must not contain spaces or garbage lines or letters different from "acgt".

you could check that when reading the file rather than in the counting part

    double start = omp_get_wtime();

    std::ifstream myfile("mouse.dat");
    std::string FileContents;
    std::string line;
    std::string whites = " \nr\t";     
    int len  = 0;
    
    while (std::getline(myfile, line))
    {
         //check line and trim right
         len  = (int)line.length();
         // we either should find no garbage or at most some trailing whitespace 
         int end = (int)line.find_first_not_of("acgt");
         if (end != std::string::npos)
         {
              // check that the garbage is only whitespace
              if (line.substr(end).find_first_not_of(whites) != std::string::npos)
              {
                  std::cout << "wrong input line\n" << line << "\n";
                  return -2;
              };
              line.resize(end);  // trim line if trailing white space
         }
         FileContents += line;
    }
    
    // finally the whole text length must be a multiple of 3
    len = FileContents.length();
    if (len%3 != 0)
    {
         std::cout << "contents is not a multiple of 3" <<  "\n";
         return -3;
    }        

Open in new window


the output of the result is like that:

    std::map<std::string, int>::iterator it = countMap.begin(), end = countMap.end();
    std::ofstream ofs("results.txt");    
    int total = len/3;

    ofs << "results: \n-------------\n";
    for (; it != end; ++it)
    {
        int count =  it->second;
        ofs << it->first << "\t" << std::right << std::setw(8) << count 
              << std::fixed << setprecision(2) <<< std::right << std::setw(8) << ((count*100.)/total) << "\n";
    }
    double timedif = omp_get_wtime() - start;
    ofs << << "\nTime: \t " << std::fixed << std::setprecision(6) << timedif << " \n";
    ofs.close();

Open in new window


Sara
SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account