public
Last active

Does a try block have a cost?

  • Download Gist
dosomething.cpp
C++
1 2 3 4 5 6 7 8 9 10 11
#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 ;
}
dosomething.h
C++
1 2 3 4 5 6
#ifndef EMS_DOSOMETHING_H_
#define EMS_DOSOMETHING_H_
 
unsigned do_something(std::vector<unsigned>& v) ;
 
#endif
main.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
#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) ;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.