• Advertisement

C++ Convert functions to linux (gcc)

Recommended Posts

Hey there,  I have this old code im trying to compile using GCC and am running into a few issues..

im trying to figure out how to convert these functions to gcc

static __int64 MyQueryPerformanceFrequency()
{
	static __int64 aFreq = 0;
	if(aFreq!=0)
		return aFreq;

	LARGE_INTEGER s1, e1, f1;
	__int64 s2, e2, f2;
	QueryPerformanceCounter(&s1);
	s2 = MyQueryPerformanceCounter();
	Sleep(50);
	e2 = MyQueryPerformanceCounter();
	QueryPerformanceCounter(&e1);
	QueryPerformanceFrequency(&f1);
	double aTime = (double)(e1.QuadPart - s1.QuadPart)/f1.QuadPart;
	f2 = (e2 - s2)/aTime;
	aFreq = f2;

	return aFreq;
}

void PerfTimer::GlobalStart(const char *theName)
{
	gPerfTimerStarted = true;
	gPerfTotalTime = 0;
	gPerfTimerStartCount = 0;
	gPerfElapsedTime = 0;

	LARGE_INTEGER anInt; QueryPerformanceCounter(&anInt);
	gPerfResetTick = anInt.QuadPart;
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void PerfTimer::GlobalStop(const char *theName)
{
	LARGE_INTEGER anInt; QueryPerformanceCounter(&anInt);
	LARGE_INTEGER aFreq; QueryPerformanceFrequency(&aFreq);
	gPerfElapsedTime = (double)(anInt.QuadPart - gPerfResetTick)/aFreq.QuadPart*1000.0;
	gPerfTimerStarted = false;
}

 

I also tried converting this function (original function is the first function below and my converted for gcc function is under that) is this correct?:

#if defined(WIN32)
static __int64 MyQueryPerformanceCounter()
{
//	LARGE_INTEGER anInt;
//	QueryPerformanceCounter(&anInt);
//	return anInt.QuadPart;
#if defined(WIN32)
	unsigned long x,y;
	_asm
	{
		rdtsc
		mov x, eax
		mov y, edx
	}

	__int64 result = y;
	result<<=32;
	result|=x;
	return result;

}
#else

static __int64 MyQueryPerformanceCounter()
{
	
	struct timeval t1, t2;
	double elapsedTime;
	
	// start timer
	gettimeofday(&t1, NULL);
	
	Sleep(50);
	
	// stop timer
	gettimeofday(&t2, NULL);
	
	// compute and print the elapsed time in millisec
	elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
	elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
	
	return elapsedTime;
	
}
#endif

Any help would be appreciated, Thank you!

Share this post


Link to post
Share on other sites
Advertisement

this is what i have now:

static __int64 MyQueryPerformanceCounter()
{
//	LARGE_INTEGER anInt;
//	QueryPerformanceCounter(&anInt);
//	return anInt.QuadPart;
	unsigned long x,y;

#if defined(WIN32)
	_asm
	{
		rdtsc
		mov x, eax
		mov y, edx
	}
#else

    __asm__ __volatile__ ("rdtsc" : "=a" (x), "=d" (y));

	// OR THIS CODE? Code to read Time Stamp Counter 
	/*
	asm(
		"	rdtsc\n"
		"	mov %%eax, %0\n"
		"	mov %%edx, %1\n"
		:
		"=a" (x),
		"=d" (y)
		);
	*/
#endif

	__int64 result = y;
	result<<=32;
	result|=x;
	return result;
}

static __int64 MyQueryPerformanceFrequency()
{
	timeval t1, t2;
	__int64 s2, e2;
	double elapsedTime;

	// start timer
	gettimeofday(&t1, NULL);
	s2 = MyQueryPerformanceCounter();
	Sleep(50);
	e2 = MyQueryPerformanceCounter();
	// stop timer
	gettimeofday(&t2, NULL);

	// compute and print the elapsed time in millisec
	elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0;      // sec to ms
	elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0;   // us to ms
//	cout << elapsedTime << " ms.\n";

	return (__int64)((e2 - s2)/elapsedTime);

}

does that look acceptable?

Share this post


Link to post
Share on other sites

gettimeofday is quite normal for measuring time. There is also std::clock http://en.cppreference.com/w/cpp/chrono/c/clock which is more portable. Don't know its precision, likely it varies between platforms.

For more extensive measuring, it might be useful to first convert timeval to a single 64 bit number, eg in nanoseconds for instance, and then compute time differences, and accumulating time.

 

Instead of the __int64, use std::int64_t standard types, which are more portable.

Share this post


Link to post
Share on other sites

There's clock_gettime in Linux. It gives you the time with nano-second resolution (but lower precision, usually), but clock_getres can be used to find the actual precision.

You may want to use the clock named CLOCK_MONOTONIC_RAW to get the actual real time that has passed.

Share this post


Link to post
Share on other sites

I've been using SDL2 SDL_GetPerformanceFrequency() and SDL_GetPerformanceCounter().

I've tracked down what (I think) is the source from

https://www.libsdl.org/tmp/SDL/src/timer/unix/SDL_systimer.c

Which seems to use  clock_gettime as rnlf_in_space suggested if supported, or fallback to gettimeofday.

Edited by lawnjelly

Share this post


Link to post
Share on other sites

For unix based systems

Header

#ifndef TimerH
#define TimerH

//#include "const_vars.h"
#ifndef WINDOWS_CMP
#include "stdint.h"

const int64_t nsec_per_sec = 1000000000;
const double ns_2_s = 1000000000.0;

typedef struct {
     int64_t start;
     int64_t stop;
 } stopWatch;

 class CStopWatch {

     stopWatch timer;

 public:
     CStopWatch() ;
     void startTimer();
     void stopTimer();
     double getElapsedTime();
     double getElapsedTimeFromStart();
     double getTime();
 };
#endif






#ifdef WINDOWS_CMP
//---------------------------------------------------------------------------

#include "windows.h"
#include <ctime>
//---------------------------------------------------------------------------

typedef struct {
     LARGE_INTEGER start;
     LARGE_INTEGER stop;
 } stopWatch;
 
 class CStopWatch {
 
 private:
 double PCFreq;// = 0.0;
     stopWatch timer;
     LARGE_INTEGER frequency;
     double LIToSecs( LARGE_INTEGER & L) ;
 public:
     CStopWatch() ;
     void startTimer();
     void stopTimer();
     double getElapsedTime();
     double getElapsedTimeFromStart();
     double getTime();
 };
#endif

#endif

Cpp

//---------------------------------------------------------------------------
#include "Timer.h"
#ifndef WINDOWS_CMP
#include "Time.h"
#include "logme.h"
//---------------------------------------------------------------------------

//returns time in miliseconds
int64_t QueryPerformanceCounter()
{
	int64_t nsec_count, nsec_per_tick;
    /*
     * clock_gettime() returns the number of secs. We translate that to number of nanosecs.
     * clock_getres() returns number of seconds per tick. We translate that to number of nanosecs per tick.
     * Number of nanosecs divided by number of nanosecs per tick - will give the number of ticks.
     */
     struct timespec ts1, ts2;

     if (clock_gettime(CLOCK_MONOTONIC, &ts1) != 0) {
    	 ALOG("FAILED TO GET TIME");
         return -1;
     }



     nsec_count = ts1.tv_nsec + ts1.tv_sec * nsec_per_sec;

     return double(nsec_count) / 1000000.0;
}




 CStopWatch::CStopWatch(){

 }

 void CStopWatch::startTimer() {
	 timer.start = QueryPerformanceCounter();
 }

 void CStopWatch::stopTimer() {
	 timer.stop = QueryPerformanceCounter();
 }

 double CStopWatch::getElapsedTime() {
	 stopTimer();
	 int64_t time = timer.stop - timer.start;
	 startTimer();

	return double(time);

 }


 double CStopWatch::getTime() {

	 int64_t time = QueryPerformanceCounter();

	return double(time);

 }

 double CStopWatch::getElapsedTimeFromStart() {
	 stopTimer();
	 int64_t time = timer.stop - timer.start;

	return double(time);

 }
#endif


#ifdef WINDOWS_CMP
      //---------------------------------------------------------------------------


#pragma hdrstop

#include "Timer.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)



 
 double CStopWatch::LIToSecs( LARGE_INTEGER & L)
 {
     return ((double)L.QuadPart / PCFreq);
 }

 CStopWatch::CStopWatch(){
     PCFreq = 0.0;
     timer.start.QuadPart=0;
	 timer.stop.QuadPart=0;
	 QueryPerformanceFrequency( &frequency ) ;
	  PCFreq = double(frequency.QuadPart);
 }
 
 void CStopWatch::startTimer( ) {
     QueryPerformanceCounter(&timer.start) ;
 }
 
 void CStopWatch::stopTimer( ) {
     QueryPerformanceCounter(&timer.stop) ;
 }
 
 double CStopWatch::getElapsedTime() {
     stopTimer();
	 LARGE_INTEGER time;
	 time.QuadPart = timer.stop.QuadPart - timer.start.QuadPart;
	 startTimer();
     return LIToSecs( time ) ;
 }

  double CStopWatch::getTime() {
      stopTimer();
	 int64_t time = timer.stop.QuadPart ();

	return LIToSecs( time ) ;

 }
  double CStopWatch::getElapsedTimeFromStart() {
	 stopTimer();
	 int64_t time = timer.stop.QuadPart - timer.start.QuadPart;

	return LIToSecs( time ) ;

 }

#endif

 

Share this post


Link to post
Share on other sites

I think you may want to use CLOCK_MONOTONIC_RAW instead of CLOCK_MONOTONIC. It doesn't make a huge difference, and mostlikely never causes any notiveable problems, but CLOCK_MONOTONIC may run slower or faster than "real" time, when the clock gets adjusted.

Basically, a correctly implemented tool to set system time on a UNIX system will not just set the new time, but rather slow down or speed up the system clock to gradually go to the new time. This is so that there are no jumps in the system time, which will throw off a bunch of things on a UNIX system.

CLOCK_MONOTONIC is subject to these adjustments, so you might experience a time where your game does not actually measure one second of realtime as one second, but rather as 1.1s or something like that. CLOCK_MONOTONIC_RAW is never sped up or slowed down.

Share this post


Link to post
Share on other sites

For sleep(50), you will need to use usleep(50000) (or, for sleep(x), use usleep(x*1000)); be careful not to use "sleep(50)", as this is denominated in seconds, rather than milliseconds. usleep() is denominated in microseconds.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Advertisement
  • Advertisement
  • Popular Now

  • Advertisement
  • Similar Content

    • By mister345
      Hi, can someone please explain why this is giving an assertion EyePosition!=0 exception?
       
      _lightBufferVS->viewMatrix = DirectX::XMMatrixLookAtLH(XMLoadFloat3(&_lightBufferVS->position), XMLoadFloat3(&_lookAt), XMLoadFloat3(&up));
      It looks like DirectX doesnt want the 2nd parameter to be a zero vector in the assertion, but I passed in a zero vector with this exact same code in another program and it ran just fine. (Here is the version of the code that worked - note XMLoadFloat3(&m_lookAt) parameter value is (0,0,0) at runtime - I debugged it - but it throws no exceptions.
          m_viewMatrix = DirectX::XMMatrixLookAtLH(XMLoadFloat3(&m_position), XMLoadFloat3(&m_lookAt), XMLoadFloat3(&up)); Here is the repo for the broken code (See LightClass) https://github.com/mister51213/DirectX11Engine/blob/master/DirectX11Engine/LightClass.cpp
      and here is the repo with the alternative version of the code that is working with a value of (0,0,0) for the second parameter.
      https://github.com/mister51213/DX11Port_SoftShadows/blob/master/Engine/lightclass.cpp
    • By Rannion
      Hi, I am sending data to peers and those data need to be retreived from a scenegraph with a mutex to lock the data.
      The process of gathering the data is taking a bit less than a ms. I'm starting the thread every time I want to gather the data. If I'm running at 60 fps, I'm starting the thread 60 times per second so is that a performance or design problem?
      Would it be much better to have the thread always running and some kind of mechanism to ask him to perform the task whenever it's needed, so around 60 or 120fps?
      Also, does starting a thread creates some memory alloc/dealloc and then produce on the long run some kind of fragmentation?
      Thank you all.
    • By stream775
      Hello!
                I wrote a simple bones system that renders a 3D model with bones using software vertex processing. The model is loaded perfectly, but I can't see any colors on it. For illustration, you can see the 3D lines list, the bones ( 32 bones ) are in correct position ( bind pose ).
       
      Now, here's the problem. When I try to render the mesh with transformations applied then I see this:
      As you can see the 3D lines are disappearing, I'm guessing the model is rendered, but the colors are not visible for whatever reason. I tried moving my camera around the line list, but all I can see is some lines disappearing due to the black color of vertices? I'm not loading any textures, am I suppose to load them?
      However, if I render the vertices without applying ANY bone transformations, then I can see it, but it's a mess, obviously. If you're wondering why it's red, I have set color of these vertices ( only half of them ) to red and the rest half is white.
      First of all, my apologies for the messy code, but here it is:
      I'm not sure if vertices are suppose to have weights in them for software vertex processing. I'm storing them in a container, so you don't see them here.
      #define CUSTOMFVF ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE ) struct CUSTOMVERTEX { D3DXVECTOR3 Position; D3DXVECTOR3 Normal; DWORD Color; }; This is how I store the vertices in container and give them red and white color:
      This is how I create the device:
      For every frame:
      This is the UpdateSkinnedMesh method:
      I have debugged bone weights and bone indices. They are okay. Bone weights add up to 1.0f, so I'm really wondering why I can't see the model with colors on it?
    • By komires
      We are pleased to announce the release of Matali Physics 4.0, the fourth major version of Matali Physics engine.
      What is Matali Physics?
      Matali Physics is an advanced, multi-platform, high-performance 3d physics engine intended for games, virtual reality and physics-based simulations. Matali Physics and add-ons form physics environment which provides complex physical simulation and physics-based modeling of objects both real and imagined. The engine is available across multiple platforms:
              Android         *BSD         iOS         Linux         OS X         SteamOS         Windows 10 UAP/UWP         Windows 7/8/8.1/10         Windows XP/Vista What's new in version 4.0?
               One extended edition of Matali Physics engine          Support for Android 8.0 Oreo, iOS 11.x and macOS High Sierra (version 10.13.x) as well as support for the latest IDEs          Matali Render 3.0 add-on with physically-based rendering (PBR), screen space ambient occlusion (SSAO) and support for Vulkan API          Matali Games add-on  
      Main benefits of using Matali Physics:
              Stable, high-performance solution supplied together with the rich set of add-ons for all major mobile and desktop platforms (both 32 and 64 bit)         Advanced samples ready to use in your own games         New features on request         Dedicated technical support         Regular updates and fixes
      The engine history in a nutshell
      Matali Physics was built in 2009 as a dedicated solution for XNA. The first complete version of the engine was released in November 2010, and it was further developed to July 2014 forming multi-platform, fully manage solution for .NET and Mono. In the meantime, from October 2013 to July 2014, was introduced simultaneous support for C++. A significant change occurred in July 2014 together with the release of version 3.0. Managed version of the engine has been abandoned, and the engine was released solely with a new native core written entirely in modern C++. Currently the engine is intensively developed as an advanced, cross-platform, high-performance 3d physics solution.
       
      If you have questions related to the latest update or use of Matali Physics engine as a stable physics solution in your projects, please don't hesitate to contact us.

      View full story
    • By JoshKlint_34394
      Today we are pleased to announce the release of Leadwerks Game Engine 4.5.
      Version 4.5 introduces support for VR headsets including the HTC Vive, Oculus Rift, and all OSVR-based hardware, allowing developers to create both room-scale and seated VR experiences. The Leadwerks virtual reality command set is robust yet incredibly simple allowing you to easily convert your existing 3D games into VR titles. To help get you started the source code for our Asteroids3D game has been updated for VR and is now freely available in the Leadwerks Games Showcase.
      Leadwerks Game Engine is uniquely well-suited for VR because of its fast performance, ease of use, and the availability of C++ programming for demanding VR games. Several optimizations for VR have been made including combining the rendering of both eyes into a single culling step. The stability and accuracy of Newton Game Dynamics means we can have in-depth physics interactions in VR.

      A new VR game template has been added to provide common VR features including teleportation locomotion and the ability to pick up and interact with objects in the environment.
      Visual Studio 2017
      We've also upgraded Leadwerks Professional Edition to build with Visual Studio 2017 so you can take advantage of the very latest Visual Studio features. Instructions for upgrading C++ projects from version 4.4 to 4.5 are available here.
      Other Improvements
      Added fog settings in editor and into map file format. New joint scripts and enhancements. Updated to Steamworks 1.41 You can pick up Leadwerks Game Engine with a discount during the Steam Winter Sale.
      About Leadwerks Software
      Leadwerks Software was founded in 2006 to make game development easy and fun. The company launched Leadwerks Game Engine on Steam in January 2014 and has experienced steady growth, now with over 20,000 paid users.  Leadwerks Game Launcher was released as an early access title in September 2015, allowing developers to publish games to Steam Workshop with no submission fee.

      View full story
  • Advertisement