Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Doom3's source code, why did they use bitshift to generate the number instead of hardcoding it?

Tags:

c++

Why did they do this:

Sys_SetPhysicalWorkMemory( 192 << 20, 1024 << 20 );   //Min = 201,326,592  Max = 1,073,741,824

Instead of this:

Sys_SetPhysicalWorkMemory( 201326592, 1073741824 );

The article I got the code from

like image 359
wyred Avatar asked Jan 15 '13 04:01

wyred


4 Answers

A neat property is that shifting a value << 10 is the same as multiplying it by 1024 (1 KiB), and << 20 is 1024*1024, (1 MiB).

Shifting by successive powers of 10 yields all of our standard units of computer storage:

  • 1 << 10 = 1 KiB (Kibibyte)
  • 1 << 20 = 1 MiB (Mebibyte)
  • 1 << 30 = 1 GiB (Gibibyte)
  • ...

So that function is expressing its arguments to Sys_SetPhysicalWorkMemory(int minBytes, int maxBytes) as 192 MB (min) and 1024 MB (max).

like image 73
Jonathon Reinhart Avatar answered Nov 19 '22 15:11

Jonathon Reinhart


Self commenting code:

192 << 20 means 192 * 2^20 = 192 * 2^10 * 2^10 = 192 * 1024 * 1024 = 192 MByte

1024 << 20 means 1024 * 2^20 = 1 GByte

Computations on constants are optimized away so nothing is lost.

like image 44
Eli Algranti Avatar answered Nov 19 '22 15:11

Eli Algranti


I might be wrong (and I didn't study the source) , but I guess it's just for readability reasons.

like image 2
KamikazeCZ Avatar answered Nov 19 '22 17:11

KamikazeCZ


I think the point (not mentioned yet) is that

All but the most basic compilers will do the shift at compilation time. Whenever you use operators with constant expressions, the compiler will be able to do this before the code is even generated. Note, that before constexpr and C++11, this did not extend to functions.

like image 1
theAgitator Avatar answered Nov 19 '22 16:11

theAgitator