I've been comparing the write times for several datatypes, and I've noticed something I find highly baffling. Firstly, here is my code:
#include <iostream>
#include <array>
#include <ctime>
#define its 1000000
#define len 1000
int main()
{
std::array<int, len> int_arr;
std::array<char, len> char_arr;
std::array<bool, len> bool_arr;
std::clock_t begin = std::clock();
for (int i = 0; i < its; ++i)
{
std::fill(int_arr.begin(), int_arr.end(), 0);
}
std::clock_t end = std::clock();
double elapsed = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "int_arr " << elapsed << std::endl;
begin = std::clock();
for (int i = 0; i < its; ++i)
{
std::fill(char_arr.begin(), char_arr.end(), 0);
}
end = std::clock();
elapsed = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "char_arr " << elapsed << std::endl;
begin = std::clock();
for (int i = 0; i < its; ++i)
{
std::fill(bool_arr.begin(), bool_arr.end(), false);
}
end = std::clock();
elapsed = double(end - begin) / CLOCKS_PER_SEC;
std::cout << "bool_arr " << elapsed << std::endl;
}
This code compares the times taken to write to arrays containing different datatypes (the repeated fills are to make the runtimes meaningfully measurable). I would expect char
and bool
to take roughly the same amount of time, since the computer still has to write the full byte into RAM. Furthermore, since int
takes 4 bytes, I would expect it to run four times as slowly.
I compiled the above code with the -O3
optimizer flag and with -std=c++11
. Contrary to my expectations, the result varies greatly! As expected, char
and bool
take the same amount of time as each other consistently (and also the same amount of time between runs). However, approximately half the time int
is only twice as slow (in this case, a factor of 2.19):
int_arr 0.043705
char_arr 0.01995
bool_arr 0.022835
And the other half of the time, it is four times as slow (in this case, a factor of 3.91):
int_arr 0.076907
char_arr 0.01965
bool_arr 0.019354
Furthermore, it is never in between! What on earth is going on here? An explanation would be greatly appreciated!
Aucun commentaire:
Enregistrer un commentaire