I have the following C99 program which measures performance of simple division operations relative to addition. However, the difftime function keeps returning 0 even though the program is clearly taking several seconds to process runAddition and runDivision with iterations set to 1 billion.
#include <stdio.h>
#include <time.h>
void runAddition(long long iterations)
{
long long temp;
for (long long i = 1; i <= iterations; i++)
{
temp = temp + i;
}
}
void runDivision(long long iterations)
{
long long temp;
// Start at 1 to avoid division by 0!
for (long long i = 1; i <= iterations; i++)
{
temp = temp / i;
}
}
int main()
{
long long iterations = 1000000000;
time_t startTime;
printf("How many iterations would you like to run of each operation? ");
scanf("%d", &iterations);
printf("Running %d additions...\n", iterations);
startTime = time(NULL);
runAddition(iterations);
printf("%d additions took %f seconds\n", iterations, difftime(time(NULL), startTime));
printf("Running %d divisions...\n", iterations);
startTime = time(NULL);
runDivision(iterations);
printf("%d divisions took %f seconds\n", iterations, difftime(time(NULL), startTime));
}
Your format string expects an
int(%d), and adouble(%f). Your arguments arelong longanddouble. You should set the first format string as%lld.When pushing arguments on the stack to call
printf, you push along longusing 8 bytes, and adoubleusing 8 bytes too. When the functionprintfreads the format string, it expects first aninton 4 bytes, and adoubleon 8 bytes.printfgets theintcorrectly as you are little-endian and the first four bytes of yourlong longare enough to represent the value.printfthen gets thedoublefor which it gets the last four bytes of thelong long, followed by the first four bytes of thedouble. As the last four bytes of thelong longare zeroes, whatprintfthinks is a double starts with four bytes with value zero, resulting in a very very tiny value for thedoubleaccording to the binary representation of doubles.