<p>I have a VB.net test application that clicks a link that opens the Microsoft Word application window and displays the document. How do I locate the Word application window so that I can grab some text from it?</p>

[{'answer_id': 61279, 'author': 'Motti', 'author_id': 3848, 'author_profile': 'https://Stackoverflow.com/users/3848', 'pm_score': 5, 'selected': True, 'text': '<p>This method has several limitations, but I still find it very useful. I\'ll list the limitations (I know of) up front and let whoever wants to use it do so at their own risk.</p>\n\n<ol>\n<li>The original version I posted over-reported time spent in recursive calls (as pointed out in the comments to the answer).</li>\n<li>It\'s not thread safe, it wasn\'t thread safe before I added the code to ignore recursion and it\'s even less thread safe now.</li>\n<li>Although it\'s very efficient if it\'s called many times (millions), it will have a measurable effect on the outcome so that scopes you measure will take longer than those you don\'t.</li>\n</ol>\n\n<hr>\n\n<p>I use this class when the problem at hand doesn\'t justify profiling all my code or I get some data from a profiler that I want to verify. Basically it sums up the time you spent in a specific block and at the end of the program outputs it to the debug stream (viewable with <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="nofollow noreferrer">DbgView</a>), including how many times the code was executed (and the average time spent of course)).</p>\n\n<pre><code>#pragma once\n#include &lt;tchar.h&gt;\n#include &lt;windows.h&gt;\n#include &lt;sstream&gt;\n#include &lt;boost/noncopyable.hpp&gt;\n\nnamespace scope_timer {\n    class time_collector : boost::noncopyable {\n        __int64 total;\n        LARGE_INTEGER start;\n        size_t times;\n        const TCHAR* name;\n\n        double cpu_frequency()\n        { // cache the CPU frequency, which doesn\'t change.\n            static double ret = 0; // store as double so devision later on is floating point and not truncating\n            if (ret == 0) {\n                LARGE_INTEGER freq;\n                QueryPerformanceFrequency(&amp;freq);\n                ret = static_cast&lt;double&gt;(freq.QuadPart);\n            }\n            return ret;\n        }\n        bool in_use;\n\n    public:\n        time_collector(const TCHAR* n)\n            : times(0)\n            , name(n)\n            , total(0)\n            , start(LARGE_INTEGER())\n            , in_use(false)\n        {\n        }\n\n        ~time_collector()\n        {\n            std::basic_ostringstream&lt;TCHAR&gt; msg;\n            msg &lt;&lt; _T("scope_timer&gt; ") &lt;&lt;  name &lt;&lt; _T(" called: ");\n\n            double seconds = total / cpu_frequency();\n            double average = seconds / times;\n\n            msg &lt;&lt; times &lt;&lt; _T(" times total time: ") &lt;&lt; seconds &lt;&lt; _T(" seconds  ")\n                &lt;&lt; _T(" (avg ") &lt;&lt; average &lt;&lt;_T(")\\n");\n            OutputDebugString(msg.str().c_str());\n        }\n\n        void add_time(__int64 ticks)\n        {\n            total += ticks;\n            ++times;\n            in_use = false;\n        }\n\n        bool aquire()\n        {\n            if (in_use)\n                return false;\n            in_use = true;\n            return true;\n        }\n    };\n\n    class one_time : boost::noncopyable {\n        LARGE_INTEGER start;\n        time_collector* collector;\n    public:\n        one_time(time_collector&amp; tc)\n        {\n            if (tc.aquire()) {\n                collector = &amp;tc;\n                QueryPerformanceCounter(&amp;start);\n            }\n            else\n                collector = 0;\n        }\n\n        ~one_time()\n        {\n            if (collector) {\n                LARGE_INTEGER end;\n                QueryPerformanceCounter(&amp;end);\n                collector-&gt;add_time(end.QuadPart - start.QuadPart);\n            }\n        }\n    };\n}\n\n// Usage TIME_THIS_SCOPE(XX); where XX is a C variable name (can begin with a number)\n#define TIME_THIS_SCOPE(name) \\\n    static scope_timer::time_collector st_time_collector_##name(_T(#name)); \\\n    scope_timer::one_time st_one_time_##name(st_time_collector_##name)\n</code></pre>\n'}, {'answer_id': 61281, 'author': 'aku', 'author_id': 1196, 'author_profile': 'https://Stackoverflow.com/users/1196', 'pm_score': 2, 'selected': False, 'text': '<p>Well, I have two code snippets. In <a href="http://en.wikipedia.org/wiki/Pseudocode" rel="nofollow noreferrer">pseudocode</a> they are looking like (it\'s a simplified version, I\'m using <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644905%28v=vs.85%29.aspx" rel="nofollow noreferrer">QueryPerformanceFrequency</a> actually):</p>\n\n<h3>First snippet:</h3>\n\n<pre><code>Timer timer = new Timer\ntimer.Start\n</code></pre>\n\n<h3>Second snippet:</h3>\n\n<pre><code>timer.Stop\nshow elapsed time\n</code></pre>\n\n<p>A bit of hot-keys kung fu, and I can say how much time this piece of code stole from my CPU.</p>\n'}, {'answer_id': 61282, 'author': 'Espo', 'author_id': 2257, 'author_profile': 'https://Stackoverflow.com/users/2257', 'pm_score': 0, 'selected': False, 'text': '<p>The article <em>Code profiler and optimizations</em> has lots of information about C++ code profiling and also has a free download link to a program/class that will show you a graphic presentation for different code paths/methods.</p>\n'}, {'answer_id': 61303, 'author': 'MrValdez', 'author_id': 1599, 'author_profile': 'https://Stackoverflow.com/users/1599', 'pm_score': 2, 'selected': False, 'text': '<p>I do my profiles by creating two classes: <code>cProfile</code> and <code>cProfileManager</code>.</p>\n\n<p><code>cProfileManager</code> will hold all the data that resulted from <code>cProfile</code>.</p>\n\n<p><code>cProfile</code> with have the following requirements:</p>\n\n<ul>\n<li><code>cProfile</code> has a constructor which initializes the current time.</li>\n<li><code>cProfile</code> has a deconstructor which sends the total time the class was alive to <code>cProfileManager</code></li>\n</ul>\n\n<p>To use these profile classes, I first make an instance of <code>cProfileManager</code>. Then, I put the code block, which I want to profile, inside curly braces. Inside the curly braces, I create a <code>cProfile</code> instance. When the code block ends, <code>cProfile</code> will send the time it took for the block of code to finish to <code>cProfileManager</code>.</p>\n\n<p><strong>Example Code</strong>\nHere\'s an example of the code (simplified):</p>\n\n<pre><code>class cProfile\n{\n    cProfile()\n    {\n        TimeStart = GetTime();\n    };\n\n    ~cProfile()\n    {\n        ProfileManager-&gt;AddProfile (GetTime() - TimeStart);\n    }\n\n    float TimeStart;\n}\n</code></pre>\n\n<p>To use <code>cProfile</code>, I would do something like this:</p>\n\n<pre><code>int main()\n{\n    printf("Start test");\n    {\n        cProfile Profile;\n        Calculate();\n    }\n    ProfileManager-&gt;OutputData();\n}\n</code></pre>\n\n<p>or this:</p>\n\n<pre><code>void foobar()\n{\n    cProfile ProfileFoobar;\n\n    foo();\n    {\n        cProfile ProfileBarCheck;\n        while (bar())\n        {\n            cProfile ProfileSpam;\n            spam();\n        }\n    }\n}\n</code></pre>\n\n<p><strong>Technical Note</strong></p>\n\n<p>This code is actually an abuse of the way scoping, constructors and deconstructors work in <a href="http://en.wikipedia.org/wiki/C_%28programming_language%29" rel="nofollow noreferrer">C++</a>. <code>cProfile</code> exists only inside the block scope (the code block we want to test). Once the program leaves the block scope, <code>cProfile</code> records the result.</p>\n\n<p><strong>Additional Enhancements</strong></p>\n\n<ul>\n<li><p>You can add a string parameter to the constructor so you can do something like this:\ncProfile Profile("Profile for complicated calculation");</p></li>\n<li><p>You can use a macro to make the code look cleaner (be careful not to abuse this. Unlike our other abuses on the language, macros can be dangerous when used).</p>\n\n<p>Example:</p>\n\n<p>#define START_PROFILE cProfile Profile(); {\n#define END_PROFILE }</p></li>\n<li><p><code>cProfileManager</code> can check how many times a block of code is called. But you would need an identifier for the block of code. The first enhancement can help identify the block. This can be useful in cases where the code you want to profile is inside a loop (like the second example aboe). You can also add the average, fastest and longest execution time the code block took.</p></li>\n<li><p>Don\'t forget to add a check to skip profiling if you are in debug mode.</p></li>\n</ul>\n'}, {'answer_id': 231590, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>I have a quick-and-dirty profiling class that can be used in profiling in even the most tight inner loops. The emphasis is on extreme light weight and simple code. The class allocates a two-dimensional array of fixed size. I then add "checkpoint" calls all over the place. When checkpoint N is reached immediately after checkpoint M, I add the time elapsed (in microseconds) to the array item [M,N]. Since this is designed to profile tight loops, I also have "start of iteration" call that resets the the "last checkpoint" variable. At the end of test, the <code>dumpResults()</code> call produces the list of all pairs of checkpoints that followed each other, together with total time accounted for and unaccounted for.</p>\n'}, {'answer_id': 231614, 'author': 'John Dibling', 'author_id': 241536, 'author_profile': 'https://Stackoverflow.com/users/241536', 'pm_score': 2, 'selected': False, 'text': '<p>Note, the following is all written specifically for Windows.</p>\n\n<p>I also have a timer class that I wrote to do quick-and-dirty profiling that uses QueryPerformanceCounter() to get high-precision timings, but with a slight difference.  My timer class doesn\'t dump the elapsed time when the Timer object falls out of scope.  Instead, it accumulates the elapsed times in to an collection.  I added a static member function, Dump(), which creates a table of elapsed times, sorted by timing category (specified in Timer\'s constructor as a string) along with some statistical analysis such as mean elapsed time, standard deviation, max and min.  I also added a Clear() static member function which clears the collection &amp; lets you start over again.</p>\n\n<p><strong>How to use the Timer class (psudocode):</strong></p>\n\n<pre><code>int CInsertBuffer::Read(char* pBuf)\n{\n       // TIMER NOTES: Avg Execution Time = ~1 ms\n       Timer timer("BufferRead");\n       :      :\n       return -1;\n}\n</code></pre>\n\n<p><strong>Sample output :</strong></p>\n\n<pre><code>Timer Precision = 418.0095 ps\n\n=== Item               Trials    Ttl Time  Avg Time  Mean Time StdDev    ===\n    AddTrade           500       7 ms      14 us     12 us     24 us\n    BufferRead         511       1:19.25   0.16 s    621 ns    2.48 s\n    BufferWrite        516       511 us    991 ns    482 ns    11 us\n    ImportPos Loop     1002      18.62 s   19 ms     77 us     0.51 s\n    ImportPosition     2         18.75 s   9.38 s    16.17 s   13.59 s\n    Insert             515       4.26 s    8 ms      5 ms      27 ms\n    recv               101       18.54 s   0.18 s    2603 ns   1.63 s\n</code></pre>\n\n<p><strong>file Timer.inl :</strong></p>\n\n<pre><code>#include &lt;map&gt;\n#include "x:\\utils\\stlext\\stringext.h"\n#include &lt;iterator&gt;\n#include &lt;set&gt;\n#include &lt;vector&gt;\n#include &lt;numeric&gt;\n#include "x:\\utils\\stlext\\algorithmext.h"\n#include &lt;math.h&gt;\n\n    class Timer\n    {\n    public:\n        Timer(const char* name)\n        {\n            label = std::safe_string(name);\n            QueryPerformanceCounter(&amp;startTime);\n        }\n\n        virtual ~Timer()\n        {\n            QueryPerformanceCounter(&amp;stopTime);\n            __int64 clocks = stopTime.QuadPart-startTime.QuadPart;\n            double elapsed = (double)clocks/(double)TimerFreq();\n            TimeMap().insert(std::make_pair(label,elapsed));\n        };\n\n        static std::string Dump(bool ClipboardAlso=true)\n        {\n            static const std::string loc = "Timer::Dump";\n\n            if( TimeMap().empty() )\n            {\n                return "No trials\\r\\n";\n            }\n\n            std::string ret = std::formatstr("\\r\\n\\r\\nTimer Precision = %s\\r\\n\\r\\n", format_elapsed(1.0/(double)TimerFreq()).c_str());\n\n            // get a list of keys\n            typedef std::set&lt;std::string&gt; keyset;\n            keyset keys;\n            std::transform(TimeMap().begin(), TimeMap().end(), std::inserter(keys, keys.begin()), extract_key());\n\n            size_t maxrows = 0;\n\n            typedef std::vector&lt;std::string&gt; strings;\n            strings lines;\n\n            static const size_t tabWidth = 9;\n\n            std::string head = std::formatstr("=== %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s ===", tabWidth*2, tabWidth*2, "Item", tabWidth, tabWidth, "Trials", tabWidth, tabWidth, "Ttl Time", tabWidth, tabWidth, "Avg Time", tabWidth, tabWidth, "Mean Time", tabWidth, tabWidth, "StdDev");\n            ret += std::formatstr("\\r\\n%s\\r\\n", head.c_str());\n            if( ClipboardAlso ) \n                lines.push_back("Item\\tTrials\\tTtl Time\\tAvg Time\\tMean Time\\tStdDev\\r\\n");\n            // dump the values for each key\n            {for( keyset::iterator key = keys.begin(); keys.end() != key; ++key )\n            {\n                time_type ttl = 0;\n                ttl = std::accumulate(TimeMap().begin(), TimeMap().end(), ttl, accum_key(*key));\n                size_t num = std::count_if( TimeMap().begin(), TimeMap().end(), match_key(*key));\n                if( num &gt; maxrows ) \n                    maxrows = num;\n                time_type avg = ttl / num;\n\n                // compute mean\n                std::vector&lt;time_type&gt; sortedTimes;\n                std::transform_if(TimeMap().begin(), TimeMap().end(), std::inserter(sortedTimes, sortedTimes.begin()), extract_val(), match_key(*key));\n                std::sort(sortedTimes.begin(), sortedTimes.end());\n                size_t mid = (size_t)floor((double)num/2.0);\n                double mean = ( num &gt; 1 &amp;&amp; (num % 2) != 0 ) ? (sortedTimes[mid]+sortedTimes[mid+1])/2.0 : sortedTimes[mid];\n                // compute variance\n                double sum = 0.0;\n                if( num &gt; 1 )\n                {\n                    for( std::vector&lt;time_type&gt;::iterator timeIt = sortedTimes.begin(); sortedTimes.end() != timeIt; ++timeIt )\n                        sum += pow(*timeIt-mean,2.0);\n                }\n                // compute std dev\n                double stddev = num &gt; 1 ? sqrt(sum/((double)num-1.0)) : 0.0;\n\n                ret += std::formatstr("    %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s %-*.*s\\r\\n", tabWidth*2, tabWidth*2, key-&gt;c_str(), tabWidth, tabWidth, std::formatstr("%d",num).c_str(), tabWidth, tabWidth, format_elapsed(ttl).c_str(), tabWidth, tabWidth, format_elapsed(avg).c_str(), tabWidth, tabWidth, format_elapsed(mean).c_str(), tabWidth, tabWidth, format_elapsed(stddev).c_str()); \n                if( ClipboardAlso )\n                    lines.push_back(std::formatstr("%s\\t%s\\t%s\\t%s\\t%s\\t%s\\r\\n", key-&gt;c_str(), std::formatstr("%d",num).c_str(), format_elapsed(ttl).c_str(), format_elapsed(avg).c_str(), format_elapsed(mean).c_str(), format_elapsed(stddev).c_str())); \n\n            }\n            }\n            ret += std::formatstr("%s\\r\\n", std::string(head.length(),\'=\').c_str());\n\n            if( ClipboardAlso )\n            {\n                // dump header row of data block\n                lines.push_back("");\n                {\n                    std::string s;\n                    for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n                    {\n                        if( key != keys.begin() )\n                            s.append("\\t");\n                        s.append(*key);\n                    }\n                    s.append("\\r\\n");\n                    lines.push_back(s);\n                }\n\n                // blow out the flat map of time values to a seperate vector of times for each key\n                typedef std::map&lt;std::string, std::vector&lt;time_type&gt; &gt; nodematrix;\n                nodematrix nodes;\n                for( Times::iterator time = TimeMap().begin(); time != TimeMap().end(); ++time )\n                    nodes[time-&gt;first].push_back(time-&gt;second);\n\n                // dump each data point\n                for( size_t row = 0; row &lt; maxrows; ++row )\n                {\n                    std::string rowDump;\n                    for( keyset::iterator key = keys.begin(); key != keys.end(); ++key )\n                    {\n                        if( key != keys.begin() )\n                            rowDump.append("\\t");\n                        if( nodes[*key].size() &gt; row )\n                            rowDump.append(std::formatstr("%f", nodes[*key][row]));\n                    }\n                    rowDump.append("\\r\\n");\n                    lines.push_back(rowDump);\n                }\n\n                // dump to the clipboard\n                std::string dump;\n                for( strings::iterator s = lines.begin(); s != lines.end(); ++s )\n                {\n                    dump.append(*s);\n                }\n\n                OpenClipboard(0);\n                EmptyClipboard();\n                HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, dump.length()+1);\n                if( hg != 0 )\n                {\n                    char* buf = (char*)GlobalLock(hg);\n                    if( buf != 0 )\n                    {\n                        std::copy(dump.begin(), dump.end(), buf);\n                        buf[dump.length()] = 0;\n                        GlobalUnlock(hg);\n                        SetClipboardData(CF_TEXT, hg);\n                    }\n                }\n                CloseClipboard();\n            }\n\n            return ret;\n        }\n\n        static void Reset()\n        {\n            TimeMap().clear();\n        }\n\n        static std::string format_elapsed(double d) \n        {\n            if( d &lt; 0.00000001 )\n            {\n                // show in ps with 4 digits\n                return std::formatstr("%0.4f ps", d * 1000000000000.0);\n            }\n            if( d &lt; 0.00001 )\n            {\n                // show in ns\n                return std::formatstr("%0.0f ns", d * 1000000000.0);\n            }\n            if( d &lt; 0.001 )\n            {\n                // show in us\n                return std::formatstr("%0.0f us", d * 1000000.0);\n            }\n            if( d &lt; 0.1 )\n            {\n                // show in ms\n                return std::formatstr("%0.0f ms", d * 1000.0);\n            }\n            if( d &lt;= 60.0 )\n            {\n                // show in seconds\n                return std::formatstr("%0.2f s", d);\n            }\n            if( d &lt; 3600.0 )\n            {\n                // show in min:sec\n                return std::formatstr("%01.0f:%02.2f", floor(d/60.0), fmod(d,60.0));\n            }\n            // show in h:min:sec\n            return std::formatstr("%01.0f:%02.0f:%02.2f", floor(d/3600.0), floor(fmod(d,3600.0)/60.0), fmod(d,60.0));\n        }\n\n    private:\n        static __int64 TimerFreq()\n        {\n            static __int64 freq = 0;\n            static bool init = false;\n            if( !init )\n            {\n                LARGE_INTEGER li;\n                QueryPerformanceFrequency(&amp;li);\n                freq = li.QuadPart;\n                init = true;\n            }\n            return freq;\n        }\n        LARGE_INTEGER startTime, stopTime;\n        std::string label;\n\n        typedef std::string key_type;\n        typedef double time_type;\n        typedef std::multimap&lt;key_type, time_type&gt; Times;\n//      static Times times;\n        static Times&amp; TimeMap()\n        {\n            static Times times_;\n            return times_;\n        }\n\n        struct extract_key : public std::unary_function&lt;Times::value_type, key_type&gt;\n        {\n            std::string operator()(Times::value_type const &amp; r) const\n            {\n                return r.first;\n            }\n        };\n\n        struct extract_val : public std::unary_function&lt;Times::value_type, time_type&gt;\n        {\n            time_type operator()(Times::value_type const &amp; r) const\n            {\n                return r.second;\n            }\n        };\n        struct match_key : public std::unary_function&lt;Times::value_type, bool&gt;\n        {\n            match_key(key_type const &amp; key_) : key(key_) {};\n            bool operator()(Times::value_type const &amp; rhs) const\n            {\n                return key == rhs.first;\n            }\n        private:\n            match_key&amp; operator=(match_key&amp;) { return * this; }\n            const key_type key;\n        };\n\n        struct accum_key : public std::binary_function&lt;time_type, Times::value_type, time_type&gt;\n        {\n            accum_key(key_type const &amp; key_) : key(key_), n(0) {};\n            time_type operator()(time_type const &amp; v, Times::value_type const &amp; rhs) const\n            {\n                if( key == rhs.first )\n                {\n                    ++n;\n                    return rhs.second + v;\n                }\n                return v;\n            }\n        private:\n            accum_key&amp; operator=(accum_key&amp;) { return * this; }\n            const Times::key_type key;\n            mutable size_t n;\n        };\n    };\n</code></pre>\n\n<p><strong>file stringext.h (provides formatstr() function):</strong></p>\n\n<pre><code>namespace std\n{\n    /*  ---\n\n    Formatted Print\n\n        template&lt;class C&gt;\n        int strprintf(basic_string&lt;C&gt;* pString, const C* pFmt, ...);\n\n        template&lt;class C&gt;\n        int vstrprintf(basic_string&lt;C&gt;* pString, const C* pFmt, va_list args);\n\n    Returns :\n\n        # characters printed to output\n\n\n    Effects :\n\n        Writes formatted data to a string.  strprintf() works exactly the same as sprintf(); see your\n        documentation for sprintf() for details of peration.  vstrprintf() also works the same as sprintf(), \n        but instead of accepting a variable paramater list it accepts a va_list argument.\n\n    Requires :\n\n        pString is a pointer to a basic_string&lt;&gt;\n\n    --- */\n\n    template&lt;class char_type&gt; int vprintf_generic(char_type* buffer, size_t bufferSize, const char_type* format, va_list argptr);\n\n    template&lt;&gt; inline int vprintf_generic&lt;char&gt;(char* buffer, size_t bufferSize, const char* format, va_list argptr)\n    {\n#       ifdef SECURE_VSPRINTF\n        return _vsnprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n#       else\n        return _vsnprintf(buffer, bufferSize-1, format, argptr);\n#       endif\n    }\n\n    template&lt;&gt; inline int vprintf_generic&lt;wchar_t&gt;(wchar_t* buffer, size_t bufferSize, const wchar_t* format, va_list argptr)\n    {\n#       ifdef SECURE_VSPRINTF\n        return _vsnwprintf_s(buffer, bufferSize-1, _TRUNCATE, format, argptr);\n#       else\n        return _vsnwprintf(buffer, bufferSize-1, format, argptr);\n#       endif\n    }\n\n    template&lt;class Type, class Traits&gt;\n    inline int vstringprintf(basic_string&lt;Type,Traits&gt; &amp; outStr, const Type* format, va_list args)\n    {\n        // prologue\n        static const size_t ChunkSize = 1024;\n        size_t curBufSize = 0;\n        outStr.erase(); \n\n        if( !format )\n        {\n            return 0;\n        }\n\n        // keep trying to write the string to an ever-increasing buffer until\n        // either we get the string written or we run out of memory\n        while( bool cont = true )\n        {\n            // allocate a local buffer\n            curBufSize += ChunkSize;\n            std::ref_ptr&lt;Type&gt; localBuffer = new Type[curBufSize];\n            if( localBuffer.get() == 0 )\n            {\n                // we ran out of memory -- nice goin\'!\n                return -1;\n            }\n            // format output to local buffer\n            int i = vprintf_generic(localBuffer.get(), curBufSize * sizeof(Type), format, args);\n            if( -1 == i )\n            {\n                // the buffer wasn\'t big enough -- try again\n                continue;\n            }\n            else if( i &lt; 0 )\n            {\n                // something wierd happened -- bail\n                return i;\n            }\n            // if we get to this point the string was written completely -- stop looping\n            outStr.assign(localBuffer.get(),i);\n            return i;\n        }\n        // unreachable code\n        return -1;\n    };\n\n    // provided for backward-compatibility\n    template&lt;class Type, class Traits&gt;\n    inline int vstrprintf(basic_string&lt;Type,Traits&gt; * outStr, const Type* format, va_list args)\n    {\n        return vstringprintf(*outStr, format, args);\n    }\n\n    template&lt;class Char, class Traits&gt;\n    inline int stringprintf(std::basic_string&lt;Char, Traits&gt; &amp; outString, const Char* format, ...)\n    {\n        va_list args;\n        va_start(args, format);\n        int retval = vstringprintf(outString, format, args);\n        va_end(args);\n        return retval;\n    }\n\n    // old function provided for backward-compatibility\n    template&lt;class Char, class Traits&gt;\n    inline int strprintf(std::basic_string&lt;Char, Traits&gt; * outString, const Char* format, ...)\n    {\n        va_list args;\n        va_start(args, format);\n        int retval = vstringprintf(*outString, format, args);\n        va_end(args);\n        return retval;\n    }\n\n    /*  ---\n\n    Inline Formatted Print\n\n        string strprintf(const char* Format, ...);\n\n    Returns :\n\n        Formatted string\n\n\n    Effects :\n\n        Writes formatted data to a string.  formatstr() works the same as sprintf(); see your\n        documentation for sprintf() for details of operation.  \n\n    --- */\n\n    template&lt;class Char&gt;\n    inline std::basic_string&lt;Char&gt; formatstr(const Char * format, ...)\n    {\n        std::string outString;\n\n        va_list args;\n        va_start(args, format);\n        vstringprintf(outString, format, args);\n        va_end(args);\n        return outString;\n    }\n};\n</code></pre>\n\n<p><strong>File algorithmext.h (provides transform_if() function) :</strong></p>\n\n<pre><code>/*  ---\n\nTransform\n25.2.3\n\n    template&lt;class InputIterator, class OutputIterator, class UnaryOperation, class Predicate&gt;\n        OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, UnaryOperation op, Predicate pred)\n\n    template&lt;class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate&gt;\n        OutputIterator transform_if(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op, Predicate pred)\n\nRequires:   \n\n    T is of type EqualityComparable (20.1.1) \n    op and binary_op have no side effects\n\nEffects :\n\n    Assigns through every iterator i in the range [result, result + (last1-first1)) a new corresponding value equal to one of:\n        1:  op( *(first1 + (i - result)) \n        2:  binary_op( *(first1 + (i - result), *(first2 + (i - result))\n\nReturns :\n\n    result + (last1 - first1)\n\nComplexity :\n\n    At most last1 - first1 applications of op or binary_op\n\n--- */\n\ntemplate&lt;class InputIterator, class OutputIterator, class UnaryFunction, class Predicate&gt;\nOutputIterator transform_if(InputIterator first, \n                            InputIterator last, \n                            OutputIterator result, \n                            UnaryFunction f, \n                            Predicate pred)\n{\n    for (; first != last; ++first)\n    {\n        if( pred(*first) )\n            *result++ = f(*first);\n    }\n    return result; \n}\n\ntemplate&lt;class InputIterator1, class InputIterator2, class OutputIterator, class BinaryOperation, class Predicate&gt;\nOutputIterator transform_if(InputIterator1 first1, \n                            InputIterator1 last1, \n                            InputIterator2 first2, \n                            OutputIterator result, \n                            BinaryOperation binary_op, \n                            Predicate pred)\n{\n    for (; first1 != last1 ; ++first1, ++first2)\n    {\n        if( pred(*first1) )\n            *result++ = binary_op(*first1,*first2);\n    }\n    return result;\n}\n</code></pre>\n'}, {'answer_id': 44489926, 'author': 'metamorphosis', 'author_id': 3454889, 'author_profile': 'https://Stackoverflow.com/users/3454889', 'pm_score': 0, 'selected': False, 'text': '<p>I wrote a simple cross-platform class called <a href="http://www.plflib.org/nanotimer.htm" rel="nofollow noreferrer">nanotimer</a> for this reason. The goal was to be as lightweight as possible so as to not interfere with actual code performance by adding too many instructions and thereby influencing the instruction cache. It is capable of getting microsecond accuracy across windows, mac and linux (and probably some unix variants).</p>\n\n<p>Basic usage:</p>\n\n<pre><code>plf::timer t;\ntimer.start();\n\n// stuff\n\ndouble elapsed = t.get_elapsed_ns(); // Get nanoseconds\n</code></pre>\n\n<p>start() also restarts the timer when necessary. "Pausing" the timer can be achieved by storing the elapsed time, then restarting the timer when "unpausing" and adding to the stored result the next time you check elapsed time.</p>\n'}]
['https://Stackoverflow.com/questions/61307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2665/']