I used C and C++ to write programs to find the number of daffodils, and found that the speed of the C++ program was only half of that of C(I use bash script to repeat run and measure time.). What causes it?
main.c
#include <stdio.h>
#include <stdbool.h>
bool is(int number)
{
int s = number;
int t = 0;
while(number)
{
t += (number % 10) * (number % 10) * (number % 10);
number /= 10;
}
return t == s;
}
int main()
{
for(int i = 100; i < 1000; i++)
{
if(is(i))
{
printf("%d\n",i);
}
}
return 0;
}
compile: gcc main.c
main.cpp
#include <iostream>
using namespace std;
bool is(int number)
{
int s = number;
int t = 0;
while(number)
{
t += (number % 10) * (number % 10) * (number % 10);
number /= 10;
}
return t == s;
}
int main()
{
for(int i = 100; i < 1000; i++)
{
if(is(i))
{
cout << i << endl;
}
}
return 0;
}
compile: g++ main.cpp
bash script(test.sh): for i in {1..1000}; do ./a.out; done
test command: time ./test.h
Solved: With static compilation, the speed is the same. It may be that the performance of libstdc++ is not good enough.