4. [15 pts Bonus] Please show a \"C\" function, called like \"int timethis \"myd
ID: 3887386 • Letter: 4
Question
4. [15 pts Bonus] Please show a "C" function, called like "int timethis "mydir",testprog")" that changes directory to the "mydir" subdirectory, and then runs (or tries to run), the testprog program, and returns the amount of time it took to run the program. If successful it returns the running time, otherwise return -1. The name of the test program, the directory, or the parameter string are in C strings, and may be different than the example. Bonus: make a modified timethis that accepts a file containing a list of directories and programs to run, and an additional parameter which specifies whether the programs should be run serially (one at a time) or in parallel (at the same time)Explanation / Answer
Below is the method to calculate the time taken to execute a given program.
myDir : directory where program to be executed resides
testprog : program to be executed
double timethis (char *myDir, char *testprog)
{
char *pDir,*cDir;
DIR *Dir;
time_t start_time, comp_time;
double total_time;
pDir = '.';
cDir = strcat(pDir,myDir); // to navigate from current dir to the subdir
Dir = opendir(cDir); // open subdir
if(Dir == NULL) // If subdir cannot be opened Dir will contain NULL
{
printf("Error opening directory %s" , myDir);
return -1;
}
start_time = time (NULL); // time before the program execution started
system(testprog);
comp_time = time (NULL); // time before the program execution ended
total_time = difftime(comp_time,start_time); // difftime function calculated the diff between two time_t type of time values
return total_time;
}
This function takes two parameters, subdir name and program to be executed. First navigate to the subdir for which we have to pass .myDir to opendir method. This is done using strcat() and opendir() functions. If opendir() is not able to open the specified directory, an error message is printed sayin "Error opening directory". If directory is opened successfully, its time to execute the program. Before execution begins, curent time is calculated by time() method which is saved as start_time and again after completion of program time is calculated and saved as comp_time. Then differance between these two time is calculated using difftime() which gives the total time taken to execute given program.
Running program sequentially: system command can be used individually to run all the programs sequentially.
Running program parallely: To execute programs parallely use execv(). This forks a child processes which executes parallely and when all the child processes completes, control is given back to timethis() function. execv() can be used to fork another process for a program as : execv("name_of_program")
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.