Size_t performance in C ++

I translated the code here in C ++ as follows

#include <iostream> using namespace std; int t = 20; bool is_evenly_divisible(const int a, const int b) { for (int i=2; i<=b; ++i) { // Line 1 if (a%i != 0) return false; } return true; } void run() { int i = 10; while (!is_evenly_divisible(i, t)) { i += 2; } cout << i << endl; } int main(int argc, char** argv) { run(); return 0; } 

With the -O3 flag in g ++ 4.8.1 compiler on Mac OSX 10.8.4, I get a time of 0.568 from user time.

Now, if I change the counter I in line 1 in the is_evenly_divisible function to size_t, the time will suddenly jump to 1.588s. This is preserved even if I change all the variables to size_t, the time increases to 1.646s

What's happening? Should size_t increase performance, not decrease it, since it is a more specific type than int?

+7
source share
2 answers

int usually the fastest popular type. This property is not compliant with the standard, but it usually applies to today's platforms. We also have things like cstdint int_fast32_t , which is more accurately guaranteed to be the fastest type, which can contain at least 32 bits - I highly recommend them for Persian-sensitive code!

size_t not intended to quickly find an integer. Its purpose is to provide an integer that can contain the size of the largest size of the object, which can contain the address space of the platform. Usually size_t equivalent to the largest native target supported by your processor, but this is not necessary.

I am going to assume that you are on a 64-bit platform. Typically, a 64-bit platform has approximately the same primary for 32-bit and 64-bit operating systems, but you ended up in one place where they usually are not: div / mod can actually be 2-3 times slower on 64-bit integer.In this case, if int is 32-bit and size_t is 64-bit, this explains the problem well.

See the Agner Fog instruction table table for details . For the Intel Sandy Bridge platform, it shows that a 32-bit div has a latency of 20-28 cycles, while a 64-bit div takes 30-94 cycles.

+14
source

The size_t size is determined by the implementation, and if you are using a 64-bit machine, most compilers will be 8 bytes long.

Operations with 8-byte integers are usually slower than with 4-byte counterparts.

+1
source

All Articles