weak_ptr_timing_test.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include <boost/config.hpp>
  2. #if defined(BOOST_MSVC)
  3. #pragma warning(disable: 4786) // identifier truncated in debug info
  4. #pragma warning(disable: 4710) // function not inlined
  5. #pragma warning(disable: 4711) // function selected for automatic inline expansion
  6. #pragma warning(disable: 4514) // unreferenced inline removed
  7. #endif
  8. //
  9. // weak_ptr_timing_test.cpp
  10. //
  11. // Copyright (c) 2002 Peter Dimov and Multi Media Ltd.
  12. // Copyright 2005 Peter Dimov
  13. //
  14. // Distributed under the Boost Software License, Version 1.0. (See
  15. // accompanying file LICENSE_1_0.txt or copy at
  16. // http://www.boost.org/LICENSE_1_0.txt)
  17. //
  18. #include <boost/shared_ptr.hpp>
  19. #include <boost/weak_ptr.hpp>
  20. #include <vector>
  21. #include <cstdio>
  22. #include <ctime>
  23. #include <cstdlib>
  24. //
  25. int const n = 29000;
  26. int const k = 2048;
  27. void test( std::vector< boost::shared_ptr<int> > & v )
  28. {
  29. using namespace std; // printf, rand
  30. std::vector< boost::weak_ptr<int> > w( v.begin(), v.end() );
  31. int s = 0, r = 0;
  32. for( int i = 0; i < n; ++i )
  33. {
  34. // randomly kill a pointer
  35. v[ rand() % k ].reset();
  36. for( int j = 0; j < k; ++j )
  37. {
  38. if( boost::shared_ptr<int> px = w[ j ].lock() )
  39. {
  40. ++s;
  41. }
  42. else
  43. {
  44. ++r;
  45. w[ j ] = v[ rand() % k ];
  46. }
  47. }
  48. }
  49. printf( "\n%d locks, %d rebinds.", s, r );
  50. }
  51. int main()
  52. {
  53. using namespace std; // printf, clock_t, clock
  54. std::vector< boost::shared_ptr<int> > v( k );
  55. for( int i = 0; i < k; ++i )
  56. {
  57. v[ i ].reset( new int( 0 ) );
  58. }
  59. clock_t t = clock();
  60. test( v );
  61. t = clock() - t;
  62. printf( "\n\n%.3f seconds.\n", static_cast<double>( t ) / CLOCKS_PER_SEC );
  63. return 0;
  64. }