473,692 Members | 2,271 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get rid of a (float) cast in timer class

Hi,

I have this following class which I use as a timer:

#include <sys/time.h>
using namespace std;

class chrono {
public:
chrono() {};
~chrono() {};

int start();
float freeze();

private:
struct timeval before_time, after_time;
struct timeval sub_chrono;
};

int chrono::start() {
return gettimeofday(&b efore_time, 0);
}

float chrono::freeze( ) {
gettimeofday(&a fter_time, 0);
timersub(&after _time, &before_time , &sub_chrono) ;

// Possible clean up required here: Remove (float) cast.
return (sub_chrono.tv_ sec + (float) sub_chrono.tv_u sec / 1000000);
}

Can anyone tell me if it's possible to remove the (float) cast in freeze()'s
return? I can't seem to figure out why it will return a long (timersub
gives long, that I get) without the cast when the function is a float.
Shouldn't a long divided by 1000000 give a float without the need for a
cast?

Thanks,
Nicolas.

--
FreeBSD 7.0-CURRENT #2: Sat Nov 26 10:55:30 EST 2005
nicblais@clk01a :/usr/obj/usr/src/sys/CLK01A
PGP? (updated 16 Nov 05) : http://www.clkroot.net/security/nb_root.asc

Nov 29 '05 #1
9 2366

Nicolas Blais wrote:
Shouldn't a long divided by 1000000 give a float without the need for a
cast?


No. Both values are integral, therefore the result is integral.
However, a long devided by 1000000.0 results in a floater. Why?
Because 1000000.0 is a floating point while without the .0 it is an
integral. Arithmatic between integral and float results in float.

I didn't look at your code to verify that this is indeed your problem -
I'm just answering the above.

Nov 29 '05 #2

roberts.n...@gm ail.com wrote:
However, a long devided by 1000000.0 results in a floater. Why?

Because 1000000.0 is a floating point while without the .0 it is an
integral. Arithmatic between integral and float results in float.


Well, to be exact, 1000000.0 is a _double_ and not a float. The result
will thus be a double and not a float.

Nov 29 '05 #3
On Mon, 28 Nov 2005 22:46:49 -0500, Nicolas Blais
<nb*****@videot ron.ca> wrote in comp.lang.c++:

You are using a header and data types not defined by the C++ language.
Hint, anything in the "sys" directory on a POSIX system is NOT part of
standard C or C++.
Hi,

I have this following class which I use as a timer:

#include <sys/time.h>
using namespace std;

class chrono {
public:
chrono() {};
~chrono() {};

int start();
float freeze();

private:
struct timeval before_time, after_time;
struct timeval sub_chrono;
};

int chrono::start() {
return gettimeofday(&b efore_time, 0);
}

float chrono::freeze( ) {
gettimeofday(&a fter_time, 0);
timersub(&after _time, &before_time , &sub_chrono) ;

// Possible clean up required here: Remove (float) cast.
return (sub_chrono.tv_ sec + (float) sub_chrono.tv_u sec / 1000000);
}

Can anyone tell me if it's possible to remove the (float) cast in freeze()'s
return? I can't seem to figure out why it will return a long (timersub
gives long, that I get) without the cast when the function is a float.
Shouldn't a long divided by 1000000 give a float without the need for a
cast?


Taking you at your word that 'sub_chrono.tv_ usec' has type long, then
no, dividing a long by another integer type will never produce a
floating point type.

Division, or addition, subtraction, or multiplication between two
values of integer type might cause promotion of one of the values to
the type of the other, if they are not of the same rank, but you are
still left with two integer values of the same type. Integer math
will be performed producing a value of the same integer type as the
operands.

Assuming that tv_usec is a long with a value between 0 and 999999,
dividing it by 1000000 will always result in a quotient of 0.

But you can remove the cast by changing the 1000000 to 1000000.0,
which will cause the promotion of tv_usec to double and produce a
double result, or to 1000000F, which will promote tv_used to float and
produce a float result.

But if you actually want 6 accurate digits after the decimal point,
and some number of digits in front of it, you had better change the
return type of the function to double, and use the 1000000.0 value.
Otherwise your fraction is not likely to be accurate on most common
implementations .

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 29 '05 #4
Ian
Nicolas Blais wrote:
float chrono::freeze( ) {
gettimeofday(&a fter_time, 0);
timersub(&after _time, &before_time , &sub_chrono) ;

// Possible clean up required here: Remove (float) cast.
return (sub_chrono.tv_ sec + (float) sub_chrono.tv_u sec / 1000000);
}

Can anyone tell me if it's possible to remove the (float) cast in freeze()'s
return? I can't seem to figure out why it will return a long (timersub
gives long, that I get) without the cast when the function is a float.
Shouldn't a long divided by 1000000 give a float without the need for a
cast?

No, it will do an integer division.

To remove the cast, change it to

return ((ub_chrono.tv_ sec*1000000+sub _chrono.tv_usec )/1000000);

Which could overflow a 32 bit int, so maybe assign ub_chrono.tv_se c to a
64 bit int before the multiplication.

Also consider using double rather than float.

Ian
Nov 29 '05 #5
On Tue, 29 Nov 2005 18:24:48 +1300, Ian <ia******@hotma il.com> wrote
in comp.lang.c++:
Nicolas Blais wrote:
float chrono::freeze( ) {
gettimeofday(&a fter_time, 0);
timersub(&after _time, &before_time , &sub_chrono) ;

// Possible clean up required here: Remove (float) cast.
return (sub_chrono.tv_ sec + (float) sub_chrono.tv_u sec / 1000000);
}

Can anyone tell me if it's possible to remove the (float) cast in freeze()'s
return? I can't seem to figure out why it will return a long (timersub
gives long, that I get) without the cast when the function is a float.
Shouldn't a long divided by 1000000 give a float without the need for a
cast?
No, it will do an integer division.

To remove the cast, change it to

return ((ub_chrono.tv_ sec*1000000+sub _chrono.tv_usec )/1000000);


This will return exactly the same result as the original expression
would _without_ the cast to float, baring overflow.
Which could overflow a 32 bit int, so maybe assign ub_chrono.tv_se c to a
64 bit int before the multiplication.

Also consider using double rather than float.

Ian


--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.l earn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Nov 29 '05 #6
Jack Klein wrote:
On Mon, 28 Nov 2005 22:46:49 -0500, Nicolas Blais
<nb*****@videot ron.ca> wrote in comp.lang.c++:

You are using a header and data types not defined by the C++ language.
Hint, anything in the "sys" directory on a POSIX system is NOT part of
standard C or C++.
Hi,

I have this following class which I use as a timer:

#include <sys/time.h>
using namespace std;

class chrono {
public:
chrono() {};
~chrono() {};

int start();
float freeze();

private:
struct timeval before_time, after_time;
struct timeval sub_chrono;
};

int chrono::start() {
return gettimeofday(&b efore_time, 0);
}

float chrono::freeze( ) {
gettimeofday(&a fter_time, 0);
timersub(&after _time, &before_time , &sub_chrono) ;

// Possible clean up required here: Remove (float) cast.
return (sub_chrono.tv_ sec + (float) sub_chrono.tv_u sec / 1000000);
}

Can anyone tell me if it's possible to remove the (float) cast in
freeze()'s
return? I can't seem to figure out why it will return a long (timersub
gives long, that I get) without the cast when the function is a float.
Shouldn't a long divided by 1000000 give a float without the need for a
cast?


Taking you at your word that 'sub_chrono.tv_ usec' has type long, then
no, dividing a long by another integer type will never produce a
floating point type.

Division, or addition, subtraction, or multiplication between two
values of integer type might cause promotion of one of the values to
the type of the other, if they are not of the same rank, but you are
still left with two integer values of the same type. Integer math
will be performed producing a value of the same integer type as the
operands.

Assuming that tv_usec is a long with a value between 0 and 999999,
dividing it by 1000000 will always result in a quotient of 0.

But you can remove the cast by changing the 1000000 to 1000000.0,
which will cause the promotion of tv_usec to double and produce a
double result, or to 1000000F, which will promote tv_used to float and
produce a float result.

But if you actually want 6 accurate digits after the decimal point,
and some number of digits in front of it, you had better change the
return type of the function to double, and use the 1000000.0 value.
Otherwise your fraction is not likely to be accurate on most common
implementations .


Thank you for your explanation! I understand better my problem (and the
solution it requires)
--
FreeBSD 7.0-CURRENT #2: Sat Nov 26 10:55:30 EST 2005
nicblais@clk01a :/usr/obj/usr/src/sys/CLK01A
PGP? (updated 16 Nov 05) : http://www.clkroot.net/security/nb_root.asc

Nov 29 '05 #7
Jack Klein wrote:
On Mon, 28 Nov 2005 22:46:49 -0500, Nicolas Blais
<nb*****@videot ron.ca> wrote in comp.lang.c++:

You are using a header and data types not defined by the C++ language.
Hint, anything in the "sys" directory on a POSIX system is NOT part of
standard C or C++.

Taking you at your word that 'sub_chrono.tv_ usec' has type long, then
no, dividing a long by another integer type will never produce a
floating point type.

Division, or addition, subtraction, or multiplication between two
values of integer type might cause promotion of one of the values to
the type of the other, if they are not of the same rank, but you are
still left with two integer values of the same type. Integer math
will be performed producing a value of the same integer type as the
operands.

Assuming that tv_usec is a long with a value between 0 and 999999,
dividing it by 1000000 will always result in a quotient of 0.

But you can remove the cast by changing the 1000000 to 1000000.0,
which will cause the promotion of tv_usec to double and produce a
double result, or to 1000000F, which will promote tv_used to float and
produce a float result.

But if you actually want 6 accurate digits after the decimal point,
and some number of digits in front of it, you had better change the
return type of the function to double, and use the 1000000.0 value.
Otherwise your fraction is not likely to be accurate on most common
implementations .


I've fixed my class with your help:

#include <ctime>
#include <sys/time.h> // Must try to get rid of this as it could be
BSD/Linux specific
using namespace std;

class chrono {
public:
chrono() {};
~chrono() {};

int start();
double freeze();

private:
struct timeval before_time, after_time;
struct timeval sub_chrono;
};
int chrono::start() {
return gettimeofday(&b efore_time, 0);
}

double chrono::freeze( ) {
gettimeofday(&a fter_time, 0);
timersub(&after _time, &before_time , &sub_chrono) ;

return (sub_chrono.tv_ sec + sub_chrono.tv_u sec / 1000000.0);
}

Now you mentionned that using <sys/time.h> breaks portability. Before I
resorted to <sys/time.h>, I actually had a class that used <ctime>, but
unfortunatly I wasn't able to get better than .2 digits precision (such as
45.99). With <sys/time.h>, I'm able to get .5 digits precision (such as
45.98676).

Of course, I would rather have my code work on most machines instead of only
the ones I'm working on. Does anyone have a suggestion for using <ctime>
with the same precision as <sys/time.h> ?

Thanks,
Nicolas.

--
FreeBSD 7.0-CURRENT #2: Sat Nov 26 10:55:30 EST 2005
nicblais@clk01a :/usr/obj/usr/src/sys/CLK01A
PGP? (updated 16 Nov 05) : http://www.clkroot.net/security/nb_root.asc

Nov 29 '05 #8
Nicolas Blais wrote:

Now you mentionned that using <sys/time.h> breaks portability. Before I
resorted to <sys/time.h>, I actually had a class that used <ctime>, but
unfortunatly I wasn't able to get better than .2 digits precision (such as
45.99). With <sys/time.h>, I'm able to get .5 digits precision (such as
45.98676).


That most likely was a leftover from 'float'.
Now that you have switched to double you got more presicion.

As a rule of thumb:

You should not use 'float' unless you
* you know what you do
* have the knowledge to fight that beast
* are willing to fight that beast
* have a very, very, very good reason
Use double instead.

--
Karl Heinz Buchegger
kb******@gascad .at
Nov 29 '05 #9

Nicolas Blais wrote:
Now you mentionned that using <sys/time.h> breaks portability. Before I
resorted to <sys/time.h>, I actually had a class that used <ctime>, but
unfortunatly I wasn't able to get better than .2 digits precision (such as
45.99). With <sys/time.h>, I'm able to get .5 digits precision (such as
45.98676).

Of course, I would rather have my code work on most machines instead of only
the ones I'm working on. Does anyone have a suggestion for using <ctime>
with the same precision as <sys/time.h> ?


You may want to take a look at Boost.Date_Time
(http://www.boost.org/doc/html/date_time.html). It has decent
precision and portability.

~KS

Nov 29 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
12614
by: Peter Scheurer | last post by:
Hi, we found some strange behavior when operating with floats and round(). The following simplified statement reproduces the problem. select 6.56 - round(convert(float, 6.56), 2) from sysusers where name = 'public'; =========== -8.88178419
4
23164
by: jaijai_kumar | last post by:
Select Cast('100.1234' as float) give me the result 100.1234 Now when I convert it back to char I want exactly 100.1234 Select Convert(char(100),Cast('100.1234' as float)) Gives me 100.123 (Here I was expecting 100.1234) When I do Select STR(Cast('100.1234' as float),25,4) I get back the result as 100.1234
6
2299
by: Dave win | last post by:
Hi all: I'm confused with the expression "(float *())". Book says that this is a cast. But, I have no idea of this expr. why could this expr ignore the variable??? Thanx!!!
19
2203
by: Jon Shemitz | last post by:
Is there a difference between a constant like "12.34f" and "(float) 12.34"? In principle, at least, the latter is a double constant being cast to a float; while the two both generate actual constants, does the latter ACTUALLY do a conversion at compile time? That is, are there constants where <constant>f != (float) <constant>
1
9069
by: Steve Wasser | last post by:
I posted this in the wrong forum, story of my life. foreach (DataRow dr1 in MyTable1.Rows) { reg = (float)dr1; prem = (float)dr1; die = (float)dr1; eth = (float)dr1; term = reg+prem+die+eth;
17
11343
by: kiplring | last post by:
float sum = (float)Math.Sqrt( floatA*floatA + floatB*floatB); I'm using DirectX with c#. But the Math class in .net framework has a problem. It is "double" base! So I'm doing type casting every line with Math class. Is there any Math library float based?
9
7130
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
5
4854
by: robert | last post by:
Turning algs for old NumPy modules into numpy code I suffer from this: Upon further processing of returns of numpy calculations, lots of data in an apps object tree will become elementary numpy types. First there is some inefficiency in calculations. And then you get data inflation and questionable dependencies - e.g. with pickle,ZODB,mpi's ... : 0.0...
3
10662
by: Arnie | last post by:
Folks, We ran into a pretty significant performance penalty when casting floats. We've identified a code workaround that we wanted to pass along but also was wondering if others had experience with this and if there is a better solution. -jeff
0
8611
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9090
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8969
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8810
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4329
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2983
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2242
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
1962
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.