본문 바로가기
개발 및 운영/프로그래밍

std::function 복사는 비싸다!

by Joseph.Lee 2019. 9. 4.

테스트코드

#include <iostream>
#include <memory>
#include <functional>
#include <ctime>

std::function<int(int,int)> temp_s;
std::unique_ptr<std::function<int(int,int)>> temp_u;

void test_1()
{
    for(int i=0; i<1000000; i++) {
        std::function<int(int,int)> copy = temp_s;
        copy(10, 20);
    }
}

void test_2()
{
    for(int i=0; i<1000000; i++) {
        temp_s(10, 20);
    }
}

void test_3()
{
    for(int i=0; i<1000000; i++) {
        (*temp_u)(10, 20);
    }
}

int main()
{
    temp_s = [](int a, int b) -> int { return a + b; };
    temp_u = std::make_unique<std::function<int(int,int)>>([](int a, int b) -> int { return a + b; });
    {
        const clock_t start = clock();
        test_1();
        const double secs = (clock()-start) / double(CLOCKS_PER_SEC);
        std::cout << "with copy: " << secs << " secs.\n";
    }
    {
        const clock_t start = clock();
        test_2();
        const double secs = (clock()-start) / double(CLOCKS_PER_SEC);
        std::cout << "without copy: " << secs << " secs.\n";
    }
    {
        const clock_t start = clock();
        test_3();
        const double secs = (clock()-start) / double(CLOCKS_PER_SEC);
        std::cout << "using unique_ptr: " << secs << " secs.\n";
    }
    
    return 0;
}

결과 :

with copy: 0.088981 secs.                                                                                                                      

without copy: 0.028533 secs.                                                                                                                   

using unique_ptr: 0.046483 secs. 

반응형

댓글