how to avoid the potential of an overflow when computing an average of times?

前端 未结 3 1284
故里飘歌
故里飘歌 2021-01-25 15:01

I am writing a function for getting the average of the clocks it takes to call a specific void (*)(void) aka void -> void function a specific number

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-25 15:54

    You can reduce potential for overflow by adding to sum the value dt/nSamples while making sure that you don't lose dt%nSamples.

    template 
    static inline ULONGLONG AveragePerformanceClocks (void (*f)(),
                                                      sampleunit_t nSamples)
    
    {
        ULONGLONG delta = 0;
        ULONGLONG sum = 0;
        sampleunit_t i;    
    
        for (i = 0; i < nSamples; ++i) {
            LARGE_INTEGER t1; 
            LARGE_INTEGER t2;
            ULONGLONG dt;
    
            QueryPerformanceCounter(&t1);
            f();        
            QueryPerformanceCounter(&t2);
    
            dt = t2.QuadPart - t1.QuadPart;
    
            // Reduce the potential for overflow.
            delta += (dt%nSamples);
            sum += (dt/nSamples);
            sum += (delta/nSamples);
            delta = (delta%nSamples);
        }
    
        return sum;
    }
    

提交回复
热议问题