Skip to content

@cire3791 /dosomething.cpp
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.