Home > Software design >  How can I get the value of a variable from a C program I've run with a bash script?
How can I get the value of a variable from a C program I've run with a bash script?

Time:11-15

I'm running my program in a for loop, passing it varying values of num_threads.

for (( j=1; j<9; j   ))
    do
        mpirun -n $j ./my_program
    done

I understand that bash will store the return value in $? automatically. However, what I am trying to do is get the runtime for a parallel program when passing it arguments of num_threads=1, so that I can use this value to find the speedup when running this program when num_threads>1. I need to return a double for this, and I had tried to return a double from main():

double main(int argc, char** argv) {
double run_time;
...

return run_time;

}

But it seems that main() can only return an int, and I get a 0 back from my bash script.

time=$?
echo $time

output:
0

CodePudding user response:

Output the value from your program.

int main(int argc, char** argv) {
    double run_time;
    ...
    
    fprintf(stderr, "%f\n", run_time);
}

Then:

for (( j=1; j<9; j   )); do
    echo -n "$j " >> speed.txt
    mpirun -n $j ./my_program 2>>speed.txt
    # or you want to see it
    # mpirun -n $j ./my_program 2> >(tee -a speed.txt >&2)
done
sort -k2g speed.txt   # -g is from GNU sort

Generally, the form double main(int, char**) is invalid - main has to have specific forms only, see https://en.cppreference.com/w/cpp/language/main_function .

  • Related