Skip to content

Instantly share code, notes, and snippets.

@cire3791
Last active December 17, 2015 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cire3791/5592977 to your computer and use it in GitHub Desktop.
Save cire3791/5592977 to your computer and use it in GitHub Desktop.
Does a try block have a cost?
#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 ;
}
#ifndef EMS_DOSOMETHING_H_
#define EMS_DOSOMETHING_H_
unsigned do_something(std::vector<unsigned>& v) ;
#endif
#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