• Advertisement
Sign in to follow this  

Unity preventing my code from being optimized away

This topic is 4251 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, Community How can I keep Visual C++ 2005 from optimizing my code away. This happens only on release build. The main reason is for benchmarking, in which the results aren't even close to what they should be.
// Test_Math.cpp : Defines the entry point for the console application.

#include "stdafx.h"
#include "..\\Math_AsmDouble\\Math_AsmDouble.h"
#include "..\\Math_AsmFloat\\Math_AsmFloat.h"
#include "..\\Math_Intrisic\\Math_Intrisic.h"
#include "..\\System_IntrisicTimer\\System_IntrisicTimer.h"

using namespace std;
using namespace SkepWorks;
using namespace SkepWorks::Math;
using namespace SkepWorks::System;

int _tmain(int argc, _TCHAR* argv[])
	IntrisicTimer timer;
	unsigned long numTimes = 1000000000;

	Math::Intrisic::Matrix3 mat(4,8,7,2,5,4,8,7,3);
	Math::Intrisic::Matrix3 mat2(5,3,7,6,5,3,4,1,5);
	Math::Intrisic::Matrix3 mat3;


// This loop is optimized away during release builds
	for( unsigned long x = 0; x < numTimes; x++)
		mat3 = mat + mat2;

	float result = timer.GetElapsedTime();

	cout << result << endl;
	cout << 1/result * numTimes << endl << endl;

	char ch;
	cin >> ch;

	return 0;

Thanks, exorcist_bob

Share this post

Link to post
Share on other sites
Guest Anonymous Poster
one technique is to include the output of your calculation in the output of the application itself i.e. print the matrices to the console or print a single value of each matrix so vc++ can't get rid of the computation.

Share this post

Link to post
Share on other sites
A simple way would be to reference 'mat3' somewhere beneath your loop (in a print statement or something of the such)

There is probably a way to do this in VS, but I don't know the ins and outs of VS very well.

Share this post

Link to post
Share on other sites
Coming up with useful synthetic benchmarks for code is a bit of a minefield since so many other factors come into play when you use the code in the real world. That said there are some things you can do to get somewhat sensible results out of something like this.

The key thing to realize is that the optimizer is very good at getting rid of redundant work so you need to make sure the work you are doing is not redundant (from the compiler's point of view). For a start you don't do anything with the value you calculate in the loop below so the optimizer trivially recognises the work is redundant and eliminates it. At the very least you need to store the results of your calculations and use them - the easiest way to do that is often to output them to the console or to a file.

The other major problem with your loop is that you perform the same calculation on every cycle through the loop, again the optimizer can see that that is redundant and eliminate the useless repetitions. To address that problem you could accumulate the results of each pass through the loop, thus (hopefully) forcing the compiler to actually carry out every iteration (i.e. change your loop to mat3 = mat3 + mat2, though that wouldn't quite be testing the same thing). Alternatively you could have an output array and two input arrays that are numTimes elements long and operate on a different array element each time through the loop, though again that's not quite testing the same thing since you introduce memory access as a factor (though that's probably a more realistic test anyway).

Even if you follow the advice above you can stil run into unexpected optimizations where the compiler can take advantage of knowledge of the whole program to do optimizations - some compilers might even be smart enough to precalculate the accumulated result of your loop if you used the accumulation I suggest above and simply return the result (I've seen Visual Studio perform similar optimizations). To get around that kind of thing you need to make sure your compiler can't know about your data - read it in from a file or use a random number generator to initialize it.

There are various other tricks you can do to disable optimizations in specific places, like using the volatitle keyword on variables, but you really need to know exactly what you're doing there since you risk disabling legitimate optimziations that the compiler is making and so rendering your test useless.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
  • Advertisement
  • Popular Tags

  • Advertisement
  • Popular Now

  • Similar Content

    • By NfiniT
      Hello!  Our team is a searching for a 2D Artist looking to add a title (whether the first one, or one of many) to his portfolio, with the opportunity to pursue a long-term partnership.
      Position & Responsibilities:
      Our team is looking for a 2D Artist to help produce finalized art assets from our current concepts and help finish our current working prototype.  This includes various stylized cartoon characters, level components/objects, background art, and possible UI elements.  The entire team can either provide you the concept art, or let you have extended creative freedom, it's up to you--whichever you feel is better suited for your process.
      Also, although this is not a requirement, if you want to expand your skill-base, you can dabble in the other aspects as well, be it animation, programming, design, narrative, etc.
      Project Description:
      Our project is titled Stanley and the Clocktower Caper, and is a casual 2D platformer with a puzzle element and child-friendly combat.  Our goal is a funny, relaxing experience that intentionally does not take itself seriously.
      Set in the steam-punk styled town, our protagonist Stanley (a sloth), is a local tinkerer and keeper of the town's clocktower.  The town and clocktower have been invaded (story-related reasoning) and are swarming with spiders who've gummed up the cogs with webs, removed gears and all-around caused chaos.  Stanley must make his way down, out of the clocktower, which will require unclogging gears, finding missing pieces to levers, switches, gear-trains, etc.  While all of this is a tall order, thankfully Stanley is an avid consumer of Slothbux, a particularly caffeinated brand of coffee which gives Stanley quite the pick-me-up (how else do you think a sloth manages to be a tinkerer and get so many odd things done!? ) and allows him to accomplish some feats of speed, agility and strength not normally attainable otherwise!
      This game will consist of Stanley escaping the tower, which is apparently going to be a pretty big tower for such a little sloth!  It must have a lot of clocks...  Pending good reception on release (this is discussed below), we would happily consider a follow-up adventure.
      Release & Other Business Stuff:
      We'll be releasing on PC, and are targeting a July release--it is an admittedly small window, but a lot of the functionality already exists and we've got a realistic perception of what we're capable of as a small team and have kept the scope of our project focused accordingly.  Distribution channel is not finalized, though the most obvious and likely candidates are Steam and Itch.io.  Price-point of the final product is TBD.
      You will be included in the rev-share, and of course that's regardless of whether you fill the role and leave or decide to stay with us for future titles.
      There are currently four of us, you will be the fifth.
      1) (Me) Our resident programmer, and dabble in both concept art & Design. 
      2) Our producer (handles scheduling, keeping things organized and on task), who also handles animation & dabbles in design.
      3) Our lead designer (story, level layout, etc.), who also does a bit of concept art
      4) Our sound engineer, who is also using the opportunity to learn a bit of programming.
      Links to Stuff:
      Working prototype--https://iconoclast209.itch.io/stanley
      If you would like to fill the role or have more questions, feel free to reach out to me on PM or on Discord at Bryant - NfiniT#5890 
      Thank you for your time!
    • By revolverolver
      First time working in 3D. Not as difficult as I thought it would be although I am pretty much a complete beginner in Blender. I chose the low poly style because I like how it looks and it is a lot easier than trying to make it look realistic.
      The gameplay is pretty much all physics driven which makes it feel satisfying to play. If it looks any fun then please check it out. I could really use a review or two.
      Here are some promo codes so that you don't have to pay a dime to download it: 
      App store link: https://itunes.apple.com/us/app/flip-trickster/id1351027839?l=en&mt=8
    • By Innoc uous
      I'm working on a space game, and I suck at art. I would love to get some help from someone who is more skilled than me. Things I need include modular space ship parts and GUI elements. Nothing too fancy, just functional so I can get a prototype put together. This could potentially become a serious project, but for now this is just a hobby project.
      In this video, you can see a few things I already completed
      :2018-02-24 20-08-13.flv2018-02-24 20-08-13.flv
    • By Innoc uous
      If you want to incorporate noise into your shaders, the Turbulance Library has you covered. Using code I gathered from this library, I made a cginc file that contains all you need to easily implement noise into your unity shaders. Who knows how this stuff works, but man, does it work well!
      Here is an example of what you can create using these noise functions.
    • By Nio Martinez
      I'll be buying a new laptop as my workstation for building games, Mostly 3D but not hard core. 
      I'm stuck at choosing between these 2 specs below. Does this really matter and if so, can some one tell my how and why it matters. 
      Intel core i5-8250U (8th gen Kabylake refresh)(6 MB Smart Cache, 1.6 GHz Base with Turbo Boost up to 3.4 GHz) 4 cores 8 threads
      RAM 8 GB DDR4 (2400 MHz)
      GPU 2 GB DDR5 Nvidia MX150 256 bit
      SSD: yes
      Intel core i7-7500U 2.70GHz Base Processor (4M Cache, up to 3.50 GHz Boost) 2 Cores, 4 Threads
      RAM 4 GB DDR4 (1800 MHz)
      GPU 2 GB DDR5 Nvidia GeForce 940MX 256 bit
      SSD: No
  • Advertisement