Почему memcpy медленнее, чем reinterpret_cast при разборе двоичных данных?

TLDR: я забыл включить оптимизацию компилятора. При включенной оптимизации производительность (почти) идентична.



Оригинальный пост

При чтении целых чисел из двоичных данных я заметил, что memcpy медленнее, чем решение для приведения.

Версия 1: reinterpret_cast, вонючий из-за потенциальных проблем с выравниванием, но также быстрее (?)

int get_int_v1(const char * data) { return *reinterpret_cast(data); }

Версия 2: memcpy, правильно и немного медленнее:

int get_int_v2(const char * data) { int result; memcpy(&result, data, sizeof(result)); return result; }

я имеюэталон на Ideone.

Для дальнейшего использования, код:

#include 
#include 
#include 
#include 
#include 
#include 
#include 

double get_current_time()
{
    timeval tv;
    gettimeofday(&tv, NULL);
    return double (tv.tv_sec) + 0.000001 * tv.tv_usec;
}

int get_int_v1(const char * data) { return *reinterpret_cast(data); }
int get_int_v2(const char * data) { int result; memcpy(&result, data, sizeof(result)); return result; }

const unsigned iterations = 200 * 1000 * 1000;

double test_v1(const char * c, unsigned & prevent_optimization)
{
    double start = get_current_time();
    for (unsigned i = 0; i != iterations; ++i)
    {
        prevent_optimization += get_int_v1(c);
    }
    return get_current_time() - start;
}

double test_v2(const char * c, unsigned & prevent_optimization)
{
    double start = get_current_time();
    for (unsigned i = 0; i != iterations; ++i)
    {
        prevent_optimization += get_int_v2(c);
    }
    return get_current_time() - start;
}

int main()
{
    srand(time(0));

    // Initialize data
    std::vector numbers(1000);
    for (std::vector::size_type i = 0; i != numbers.size(); ++i)
    {
        numbers[i] = i;
    }

    // Repeat benchmark 4 times.
    for (unsigned i = 0; i != 4; ++i)
    {
        unsigned p = 0;
        std::vector::size_type index = rand() % numbers.size();
        const char * c = reinterpret_cast(&numbers[index]);    
        std::cout < "v1: " < test_v1(c, p) < std::endl;
        std::cout < "v2: " < test_v2(c, p) < std::endl < std::endl;
    }
}

Ответы на вопрос(3)

Ваш ответ на вопрос