473,663 Members | 2,877 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C or C++ in measuring microseconds

7 New Member
Hi guys,

I have tried a lot of code and read forums discussing about C or C++ functions that measures time in microsecond, but there still seems to be confusions about that. Can anyone tell me again how do I get the time up to 1 microsecond in resolution? It doesn't need to be very precise in measuring the time, but at least need to be able to measure 1 microsecond the minimum. I saw in some forum that says usleep() gives microsecond delay, but when I check the source code and try it out myself, it seems like it can only give up until 1 millisecond in resolution (please advise me if I am wrong).

There is also a function call select() that can give up until microsecond, but I could not compile it. The following four lines of codes are from an example, but it doesn't work for me.

[PHP]struct tv time;
time.tv_sec = 10;//num_seconds_to_ sleep;
time.tv_usec = 10;//num_microsecond s_to_sleep;

select(NULL,NUL L,NULL,& time);[/PHP]

(line 1) error C2079: 'time' uses undefined struct 'wmain::tv'
(line 2) error C2228: left of '.tv_sec' must have class/struct/union
(line 3) error C2228: left of '.tv_usec' must have class/struct/union
(line 5) error C2660: 'select' : function does not take 4 arguments

These errors might be because I did not include a proper .h file. But when I followed the example code and include <unistd.h> and <sys/time.h>, another error which says "fatal error C1083: Cannot open include file: 'unistd.h': No such file or directory" came out. Is that because those are for linux? I am using Windows XP by the way.

Thanks a lot.
Sep 11 '08 #1
7 18320
Laharl
849 Recognized Expert Contributor
Yep, those files are for POSIX systems, aka Linux/Unix (unistd actually stands for unix standard). The select function does exist in Windows, but it works differently. Don't ask me how, but I know it does.

There's a function in the standard header <time.h> or <ctime> (for C/C++, respectively) that can measure time in clock cycles and defines a macro CLOCKS_PER_SEC, giving you seconds. From there, you can convert to milliseconds. Unfortunately, timing code is a real pain to do accurately, since the OS is constantly a) switching processes in and out and b) constantly interrupting the current process. As a general rule, the following will work:

Expand|Select|Wrap|Line Numbers
  1. #include <ctime>
  2.  
  3. int main(){
  4.      clock_t start = clock(); //clock_t is probably an unsigned int...but it's platform specific
  5.      //code to time goes here
  6.      clock_t end = clock();
  7. }
Sep 11 '08 #2
i12know
7 New Member
I have tried that method, but it only able to measure until 1 millisecond, but I need to measure 1 or 2 microsecond at least, thats why the code doesn't really work fine for me.

Or I would say like that, I would like to generate an output like a clock signal, with a period of about 3 or 4 microseconds, thats why I need to toggle the output signal every 1 or 2 microsecond. One thing to note is that, of course is good to have the signal period accurately, but it is not a must in my case.

Any better way to do that?

Thanks in advance.
Sep 11 '08 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
You run the code to be timed say 10,000,000 times. Then subtract the start time from the end time and divide by 10,000,000 to get your answer.
Sep 11 '08 #4
donbock
2,426 Recognized Expert Top Contributor
Or I would say like that, I would like to generate an output like a clock signal, with a period of about 3 or 4 microseconds, thats why I need to toggle the output signal every 1 or 2 microsecond.
Toggling an output every microsecond or two solely via software makes it sound like you're working with an embedded system. Is that true?

What is your target system?
> What processor?
> What operating system?
> What compiler are you using?
> Is it a cross-compiler?

Are you sure you have to accomplish this feat of precise timing solely through software? That is, does your target system have a timer output that you can program to produce a nice stable square wave at the desired frequency.

Cheers,
donbock
Sep 11 '08 #5
i12know
7 New Member
Basically, I am trying to establish communication between PC's parallel port and a microconverter which has a 8051 microcontroller on it. I am using the SPI functionality on the microconverter to communicate with the PC. In this case, as the PC would be the master device, it has to generate a clock signal and transmit to the microconverter, which is the slave device, through the SCLOCK pin.

From what I know is, the period of the clock signal need not be that accurate, as the master and slave devices both receive and transmit the data only at negative and positive edge, so it seems doesn't really matter whether the clock signal will stay at high and low level for the exact same time.

I am not sure what is the operating system for the microconverter, but it is a 8051 microcontroller , and I am using Keil C compiler to compile the machine code, which I believe is a cross-compiler.

Hope that clears up the confusion.
Sep 12 '08 #6
newb16
687 Contributor
[quote=i12know]

, so it seems doesn't really matter whether the clock signal will stay at high and low level for the exact same time.
It doesn not matter either - look at datasheet of microcontroller - any duration larger than minimal is ok.

I am not sure what is the operating system for the microconverter, but it is a 8051 microcontroller , and I am using Keil C compiler to compile the machine code, which I believe is a cross-compiler.
Operating system for PC.
Sep 12 '08 #7
Banfa
9,065 Recognized Expert Moderator Expert
Have you considered something like a USB - SPI adaptor?

In my experience PCs are not terribly reliable at anything below a few milliseconds because normally they are running so many processes that they don't service the timer often enough.

Do you have to talk to this micro-controller using SPI? is there no RS232 interface available?

Alternatively if the USB adaptor is too expensive, or you require many of them (in a large scale commercial project say) it may be cheaper and easier to get another cheap micro-processor and build an RS232 to SPI converter allowing you to use the serial port of the PC.


So of these suggestions by be infeasible or on investigation silly but my point is there are many more ways out of the problem of getting a PCto talk on an SPI bus that programming the parallel port to do something it isn't really designed for.

The point is that in your environment, which is actually solving a systems problem you should not necessarily try to program your way out of every problem. There is no point spending £1000 writing software to solve a problem if you can solve the same problem by buying a £100 USB dongle. However I do see people do this very thing on a monthly basis.
Sep 12 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2324
by: Mudge | last post by:
I'm writing PHP Web sites that are database driven with mysql. I'm looking for ways to measure the performance (speed) of my php code, so that I can find ways to write the fastest php code. Any suggestions? Nick
3
5057
by: ´_¬¡¤F | last post by:
I can include time.h and use time() to get UTC seconds,but how can I get microseconds ?? My OS is windows. -- >> ¥xÆW¬ì¤j¸ê¤u¨t ²M¬y¯¸ # ntust.org #
2
733
by: Michael Evans | last post by:
First, we rely on a stable update rate so that our physics and dynamics calculations and integrations are based on a known interval and therefore are true-to-life. Second, the graphics positions in our image generators are updated by this dynamics application, and we need to update them at the rate they are being refreshed so that we don't get any stutter from frames being used twice or having to be thrown out. Without microsecond...
2
6913
by: In. Martin Prá¹ek | last post by:
I I read the documentation well (PG 7.3.3 ) , i see that there is not a native support for data type UNIX TIMESTAMP and "unix timestamp expressed as microseconds" ie there it is impossible to direct insert and select seconds_from _Epoch seconds_from _Epoch (period) microseconds_part seconds_from _Epochmicroseconds_part without some data conversion ?
0
1591
by: NTPT | last post by:
I read the documentation well (PG 7.3.3 ) , it seems that there is not a native support for data type UNIX TIMESTAMP and "unix timestamp expressedas microseconds" ie there it is impossible to direct insert and select seconds_from _Epoch seconds_from _Epoch (period) microseconds_part seconds_from _Epoch(no period here)microseconds_part without some data conversion ?
74
7716
by: Dominik Wallner | last post by:
Hi! I'm currently implementing a program which measures voltages through an external USB-AD-converter. It should output those values as time/voltage pairs. My problem is to measure the time to output (time elapsed since program start would do just fine) - it should be as precise as possible, as there may be only differences in milliseconds between two measurements.
5
5445
by: mroeloffs | last post by:
Hi I have a time in microseconds, for example 0x8C905CBA7F84AF4. I want this to a normal view in hh:mm:ss DD:MM:YYYY. I tried with datetime, but it only takes a max of 1000000 microseconds is there another solution?
3
8911
by: Francesco | last post by:
I search a function to calculate microseconds in a time istant
9
3300
by: Ross | last post by:
I'm a newbie at this, and have searched a lot but can't find something that seems appropriate for measuring a recurring elapsed time. Creating an object with: var mydate = new Date(); seems clear, as is creating a second: nowTime = new Date(); and getting a difference between the two. My quesiton is what if you have many, maybe thousands of intervals you wish to measure? Should I do: nowTime = new Date(); with every pass of a...
0
8345
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8858
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
8771
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...
1
8548
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8634
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
7371
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6186
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5657
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2763
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

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.