#include &
#include &
#include&
using namespace std;

void QuickSort(int arr[],int lo,int hi)
{
if(lo&>=hi){return;}
int first=lo;
int last=hi;
int key=arr[lo];
while(last&>first)
{
while(first&=key)
--last;
arr[first] = arr[last];
while(first&&>n;
for(int i=0;i&

代码如上,测量一个快排演算法的运行时间,最后出来总为0,是我的计时有问题呢还是电脑太快了??

谢谢大家的解答...中午睡了一觉起来1000个排序都能看到时间了 上午100000个都没有时间.电脑有毒..


你选用的计时器貌似在windows上的精度为33ms(或者更低,反正不精确),我一般都是用另一个api获取远超乎你想像的精确度:QueryPerformanceFrequency,用法可以百度。

我一般就用这个东西优化我的演算法


如果是兼容C++11的编译器,取时间的话用chrono吧……

关于时间复杂度,1微秒为10^-6秒,而讲道理qsort这种东西呢是O(nlogn),10^6个数都不超过1秒,而10^5大体上应该也就100毫秒以内,扔进去十来个数应当只有数十微秒的计算时间。

要知道很多非常先进的OS里(对的就是说windows+cl组合),取到微秒级计时器是需要一些比较非常规手段的,而往往你取到的只是个毫秒计时器,有些所谓微秒级往往只是毫秒乘了个1000,几乎完全没有意义。


把数据量调大一些。还有 GetSystemTimeAsFileTime 可能精度不够,如果需要精确计时使用 QueryPerformanceCounter 更佳。使用说明见QueryPerformanceCounter function,精度可以达到 &<1us

示例:

LARGE_INTEGER nf, n1, n2;
QueryPerformanceFrequency(nf); // 获取计数器频率
QueryPerformanceCounter(n1); // 获取开始时间
// ...
QueryPerformanceCounter(n2); // 获取结束时间
cout &(static_cast&(n2.QuadPart - n1.QuadPart) / nf.QuadPart * 1000000) &

n = 10000 时 GetSystemTimeAsFileTime QueryPerformanceCounter 测出来分别是 0us 和 1500us左右,这里 GetSystemTimeAsFileTime 的精度已经不够用了(话说两个 dwLowDateTime 直接真的大丈夫么……以及 FILETME 的单位是100ns)。比 GetSystemTimeAsFileTime 精确到不知道那里去了(逃

另外之前试过 std::chrono::high_resolution_clock *在某些实现中*似乎有的实现对于需要很精确测速的地方不够,还得自己用 QueryPerformanceCounter 弄一个……可以参考一下 @Milo Yip 写的 Timer 实现:https://github.com/miloyip/itoa-benchmark/blob/master/src/timer.h

附:用 QueryPerformanceCounter 实现符合concept TrivialClock的真·高精度时钟与 std::chrono::high_resolution_clock 的对比

#include &
#include &
#include &

#include &

class HighResolutionClock {

public:

using rep = double;
using period = std::ratio&<1&>;
using duration = std::chrono::duration&;
using time_point = std::chrono::time_point&;

static constexpr bool is_steady = false;

static time_point now() {

LARGE_INTEGER nf, n;
QueryPerformanceFrequency(nf);
QueryPerformanceCounter(n);
return time_point(duration(static_cast&(n.QuadPart) / nf.QuadPart));

}

};

int main() {

auto t11 = std::chrono::high_resolution_clock::now();
auto t21 = HighResolutionClock::now();
for(int i = 0; i &< 100000; ++i); auto t12 = std::chrono::high_resolution_clock::now(); auto t22 = HighResolutionClock::now(); std::cout &(t12 - t11).count() &(t22 - t21).count() &

编译器 GCC 5.1.0 ,关闭优化运行,输出:

std::chrono::high_resolution_clock: 0us或1000us
HighResolutionClock: 在280us上下浮动


用 std::chrono::high_resolution_clock 来计时, 可以精确到us.

auto t1 = chrono::high_resolution_clock::now();

//TODO

auto t2 = chrono::high_resolution_clock::now();

auto time_span = chrono::duration_cast&&>(t2 - t1);

std::cout &


可以考虑试试Visual Studio 2015 Community这里的这个功能


请自己计算一下100000的数据量,快排的时间复杂度为O(nlogn),算下来大概1660964,现在最垃圾的电脑1s也能跑1e8,也就是0.016s跑完,你电脑再稍微好一点就根本测不出来了。把数据量调到1e8,让猴排教你做人(
连1s都没有吗?
代码没问题 而是运行过快无法统计时间的话 解决办法是 多循环几次
java写的快排十万个数据是5ms不到的样子,而且还是几年前的渣电脑,感觉应该是定时器精度不够,数据量放大到千万级别试试?
试试std::chrono::high_resolution_clock?
推荐阅读:
相关文章