Question:
I have made two codes in C and python to identify prime numbers, I have to execute it in bash with a for loop until the first 5 numbers, so far so good, but they ask me to calculate the execution time of that for loop without using the time
command … so I don't know how to calculate it.
I am attaching my code in bash the name of the file in python and C is prime.
#!/bin/bash
echo "programa en C"
gcc primo.c -o primo
for ((i=0; i<=5;i=i+1))
do
./primo $i
done
echo "Programa en python "
for ((i=0; i<=5;i=i+1))
do
python3 primo.py $i
done
Answer:
The date command gives you the +%s
option which returns the seconds that have passed from the first day of the year 1970 to the precise moment you use the date +%s
command, and we have the +%N
option for nanoseconds. (one second = one billion nanoseconds). We will calculate the execution time of your c program with all 9 digits corresponding to nanoseconds:
#Obtenemos los segundos como punto de partida y usamos un formato +%s.%N
#para agregar un punto decimal para despues restar.
declare -r TiempoInicial=$(date +%s.%N)
echo "programa en C"
gcc primo.c -o primo
for ((i=0; i<=5;i=i+1))
do
./primo $i
done
#Una vez se acaba el for podemos restar el tiempo actual con el tiempo
#guardado antes de ejecutar el for y obtendremos el tiempo de ejecución.
declare -r TiempoFinal=$(date +%s.%N)
declare -r TiempoDeEjecucion=$(echo "$TiempoFinal-$TiempoInicial" | bc)
echo "Transcurrieron $TiempoDeEjecucion segundos para el programa en c"
That should give you something like:
programa en C
Transcurrieron 3.005704120 segundos para el programa en c
Now we will do it with the python program but using only three decimal digits corresponding to the nanoseconds, this will make it easier for us to better read the elapsed time:
declare -r TiempoInicial=$(date +%s.%N)
echo "programa en Python"
for ((i=0; i<=5;i=i+1))
do
python3 primo.py $i
done
declare -r TiempoFinal=$(date +%s.%N)
#Sabemos que los nanosegundos siempre son 9 dígitos y si queremos
#solamente 3 entonces quitaremos los 6 últimos ya que 9 - 6 = 3
declare -r TiempoDeEjecucion=$(echo "$TiempoFinal-$TiempoInicial" | bc)
echo "Transcurrieron ${TiempoDeEjecucion::-6} segundos para el programa en python"
That should give you something like:
programa en Python
Transcurrieron 3.006 segundos para el programa en python