The clock()
function has a finite resolution. On VC2013 it is once per millisec. (Your system may vary). If you call clock()
twice in the same millisecond (or whatever) you get the same value.
in <ctime>
there is a constant CLOCKS_PER_SEC
which tells you how many ticks per second. For VC2012 that is 1000.
** Update 1 **
You said you're in Windows. Here's some Win-specific code that gets higher resolution time. If I get time I'll try to do something portable.
#include <iostream>
#include <vector>
#include <ctime>
#include <Windows.h>
int main()
{
::srand(::time(NULL));
FILETIME ftStart, ftEnd;
const int nMax = 1000*1000;
std::vector<unsigned> vBuff(nMax);
int nTotal=0;
::GetSystemTimeAsFileTime(&ftStart);
for (int i=0;i<nMax;i++)
{
vBuff[i]=rand();
}
for(int j=0;j<nMax;j++)
{
nTotal+=vBuff[j];
}
::GetSystemTimeAsFileTime(&ftEnd);
double dElapsed = (ftEnd.dwLowDateTime - ftStart.dwLowDateTime) / 10000.0;
std::cout << "Elapsed time = " << dElapsed << " millisec\n";
return 0;
}
** Update 2 **
Ok, here's the portable version.
#include <iostream>
#include <vector>
#include <ctime>
#include <chrono>
// abbreviations to avoid long lines
typedef std::chrono::high_resolution_clock Clock_t;
typedef std::chrono::time_point<Clock_t> TimePoint_t;
typedef std::chrono::microseconds usec;
uint64_t ToUsec(Clock_t::duration t)
{
return std::chrono::duration_cast<usec>(t).count();
}
int main()
{
::srand(static_cast<unsigned>(::time(nullptr)));
const int nMax = 1000*1000;
std::vector<unsigned> vBuff(nMax);
int nTotal=0;
TimePoint_t tStart(Clock_t::now());
for (int i=0;i<nMax;i++)
{
vBuff[i]=rand();
}
for(int j=0;j<nMax;j++)
{
nTotal+=vBuff[j];
}
TimePoint_t tEnd(Clock_t::now());
uint64_t nMicroSec = ToUsec(tEnd - tStart);
std::cout << "Elapsed time = "
<< nMicroSec / 1000.0
<< " millisec\n";
return 0;
}