Last active
December 17, 2015 10:09
-
-
Save cire3791/5592977 to your computer and use it in GitHub Desktop.
Does a try block have a cost?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include "dosomething.h" | |
unsigned do_something( std::vector<unsigned>& v) | |
{ | |
unsigned total = 0 ; | |
for ( unsigned i=0; i<v.size(); ++i ) | |
total += (v[i] += i) ; | |
return total ; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef EMS_DOSOMETHING_H_ | |
#define EMS_DOSOMETHING_H_ | |
unsigned do_something(std::vector<unsigned>& v) ; | |
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <chrono> | |
#include <iostream> | |
#include <limits> | |
#include "dosomething.h" | |
const unsigned iterations = std::numeric_limits<unsigned>::max() ; | |
const unsigned vector_size = 2 ; | |
std::chrono::milliseconds test_with_try() ; | |
std::chrono::milliseconds test_with_no_try() ; | |
int main() | |
{ | |
auto throw_duration = test_with_try() ; | |
std::cout << "Try block: " << throw_duration.count() << "ms\n" ; | |
auto no_throw_duration = test_with_no_try() ; | |
std::cout << "No try block: " << no_throw_duration.count() << "ms\n" ; | |
auto difference = throw_duration - no_throw_duration ; | |
std::cout << "Difference of " | |
<< (static_cast<double>(difference.count()) / no_throw_duration.count()) * 100 | |
<< "%\n" ; | |
} | |
std::chrono::milliseconds test_with_no_try() | |
{ | |
std::vector<unsigned> v(vector_size) ; | |
auto begin = std::chrono::high_resolution_clock::now() ; | |
for ( unsigned i=0; i<iterations; ++i ) | |
{ | |
do_something(v) ; | |
} | |
auto end = std::chrono::high_resolution_clock::now() ; | |
return std::chrono::duration_cast<std::chrono::milliseconds>(end-begin) ; | |
} | |
std::chrono::milliseconds test_with_try() | |
{ | |
std::vector<unsigned> v(vector_size) ; | |
auto begin = std::chrono::high_resolution_clock::now() ; | |
for ( unsigned i=0; i<iterations; ++i ) | |
{ | |
try { | |
do_something(v) ; | |
} | |
catch(std::exception& ex) | |
{ | |
std::cout << ex.what() << '\n' ; | |
} | |
} | |
auto end = std::chrono::high_resolution_clock::now() ; | |
return std::chrono::duration_cast<std::chrono::milliseconds>(end-begin) ; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment