Автор Тема: CBuilder  (Прочитано 14532 раз)

kats

  • Гость
CBuilder
« : 08-01-2005, 00:00:00 »
Народ, есть кого CBuilder версии 6 и выше, ато есть 6 версия, но там глюки возникают разные. И ещё вопрос по праграммированию на нём: есть процедура, которая может выполняться различное время(в зависимости от начальных данных), а нужно задать так, чтобы она выполнялась не менее, чем какое-либо определённое время.(например,если процедура выполнилась за врея 0.1 сек, а надо 1 сек, то поставить задержку времени выполнения. Если же время выполнения будет больше 1 сек., то задержки не должно быть) Как такое сделать?
« Последнее редактирование: 08-01-2005, 00:00:00 от kats »

Оффлайн Lucefer

  • Старожил
  • *****
  • Сообщений: 1947
  • Карма: +80/-16
  • Гитлер капут!
Re: CBuilder
« Ответ #1 : 10-01-2005, 00:00:00 »
> Если же время выполнения будет больше 1 сек., то задержки не должно быть
---
А время сравнивать до и после вызова процедуры - не судьба? ;-)

Могу VS подкинуть если надо.
Каждый имеет право свободно искать, получать, передавать, производить и распространять информацию любым законным способом. Перечень сведений, составляющих государственную тайну, определяется федеральным законом.
Статья 29.п4. Конституция РФ.

kats

  • Гость
Re: CBuilder
« Ответ #2 : 11-01-2005, 00:00:00 »
Это приходило в голову(но самого оператора незнаю), только время должно исчисляться с  точностью до миллисекунд, вот нашёл такую функцию:
TimeStampToMSecs      --  возвращает 64-разрядное значение числа миллисекунд.

kats

  • Гость
Re: CBuilder
« Ответ #3 : 11-01-2005, 00:00:00 »
Цитировать
> Могу VS подкинуть если надо.

за VS спасибо, но не надо, надо именно CBuilder неглючный:)
« Последнее редактирование: 11-01-2005, 00:00:00 от kats »

Оффлайн Lucefer

  • Старожил
  • *****
  • Сообщений: 1947
  • Карма: +80/-16
  • Гитлер капут!
Пример кода из хэлпа
« Ответ #4 : 11-01-2005, 00:00:00 »
difftime - Finds the difference between two times.
double difftime(
  time_t timer1,
  time_t timer0
);
Parameters
timer1
Ending time.
timer0
Beginning time.
Return Value
difftime returns the elapsed time in seconds, from timer0 to timer1. The value returned is a double-precision, floating-point number.

Remarks
The difftime function computes the difference between the two supplied time values timer0 and timer1.
Requirements
RoutineRequired headerCompatibility
difftime<time.h>ANSI, Win 98, Win Me, Win NT, Win 2000, Win XP

Example

// crt_difftime.c
/* This program calculates the amount of time
* needed to do a floating-point multiply 500 million times.
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main( void )
{
  time_t   start, finish;
  long loop;
  double   result, elapsed_time;

  printf( "Multiplying 2 floating point numbers 500 million times...\n" );
 
  time( &start );
  for( loop = 0; loop < 500000000; loop++ )
     result = 3.63 * 5.27;
  time( &finish );

  elapsed_time = difftime( finish, start );
  printf( "\nProgram takes %6.0f seconds.\n", elapsed_time );
}
Каждый имеет право свободно искать, получать, передавать, производить и распространять информацию любым законным способом. Перечень сведений, составляющих государственную тайну, определяется федеральным законом.
Статья 29.п4. Конституция РФ.

Оффлайн Lucefer

  • Старожил
  • *****
  • Сообщений: 1947
  • Карма: +80/-16
  • Гитлер капут!
и на счёт миллисекунд
« Ответ #5 : 11-01-2005, 00:00:00 »
time, _time64
Get the system time.

time_t time(
  time_t *timer
);
__time64_t _time64(
  __time64_t *timer
);
Parameters
timer
Pointer to the storage location for time.
Return Value
Return the time in elapsed seconds. There is no error return.

A call to time or _time64 can fail, however, if the date passed to the function is:
Before midnight, January 1, 1970.
After 19:14:07, January 18, 2038, UTC (using time and time_t).
After 23:59:59, December 31, 3000, UTC (using _time64 and __time64_t).

Remarks
The time function returns the number of seconds elapsed since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC), according to the system clock. The return value is stored in the location given by timer. This parameter may be NULL, in which case the return value is not stored.

Example


// crt_times.c
/* This program demonstrates these time and date functions:
*      _time64         _ftime64        _ctime64     asctime
*      _localtime64    _gmtime64       _mktime64    _tzset
*      _strtime        _strdate        strftime
*
* Also the global variable:
*      _tzname
*/

#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>

int main()
{
   char tmpbuf[128], ampm[] = "AM";
   __time64_t ltime;
   struct __timeb64 tstruct;
   struct tm *today, *gmt, xmas = { 0, 0, 12, 25, 11, 93 };

   /* Set time zone from TZ environment variable. If TZ is not set,
    * the operating system is queried to obtain the default value
    * for the variable.
    */
   _tzset();

   /* Display operating system-style date and time. */
   _strtime( tmpbuf );
   printf( "OS time:\t\t\t\t%s\n", tmpbuf );
   _strdate( tmpbuf );
   printf( "OS date:\t\t\t\t%s\n", tmpbuf );

   /* Get UNIX-style time and display as number and string. */
   _time64( &ltime );
   printf( "Time in seconds since UTC 1/1/70:\t%ld\n", ltime );
   printf( "UNIX time and date:\t\t\t%s", _ctime64( &ltime ) );

   /* Display UTC. */
   gmt = _gmtime64( &ltime );
   printf( "Coordinated universal time:\t\t%s", asctime( gmt ) );

   /* Convert to time structure and adjust for PM if necessary. */
   today = _localtime64( &ltime );
   if( today->tm_hour >= 12 )
   {
  strcpy( ampm, "PM" );
  today->tm_hour -= 12;
   }
   if( today->tm_hour == 0 )  /* Adjust if midnight hour. */
  today->tm_hour = 12;

   /* Note how pointer addition is used to skip the first 11
    * characters and printf is used to trim off terminating
    * characters.
    */
   printf( "12-hour time:\t\t\t\t%.8s %s\n",
      asctime( today ) + 11, ampm );

   /* Print additional time information. */
   _ftime64( &tstruct );
   printf( "Plus milliseconds:\t\t\t%u\n", tstruct.millitm );
   printf( "Zone difference in hours from UTC:\t%u\n",
            tstruct.timezone/60 );
   printf( "Time zone name:\t\t\t\t%s\n", _tzname[0] );
   printf( "Daylight savings:\t\t\t%s\n",
            tstruct.dstflag ? "YES" : "NO" );

   /* Make time for noon on Christmas, 1993. */
   if( _mktime64( &xmas ) != (__time64_t)-1 )
  printf( "Christmas\t\t\t\t%s\n", asctime( &xmas ) );

   /* Use time structure to build a customized time string. */
   today = _localtime64( &ltime );

   /* Use strftime to build a customized time string. */
   strftime( tmpbuf, 128,
        "Today is %A, day %d of %B in the year %Y.\n", today );
   printf( tmpbuf );
}


Sample Output

OS time:                                14:15:49
OS date:                                02/07/02
Time in seconds since UTC 1/1/70:       1013120149
UNIX time and date:                     Thu Feb 07 14:15:49 2002
Coordinated universal time:             Thu Feb 07 22:15:49 2002
12-hour time:                           02:15:49 PM
Plus milliseconds:                      455
Zone difference in hours from UTC:      8
Time zone name:                         Pacific Standard Time
Daylight savings:                       NO
Christmas                               Sat Dec 25 12:00:00 1993

Today is Thursday, day 07 of February in the year 2002.
Каждый имеет право свободно искать, получать, передавать, производить и распространять информацию любым законным способом. Перечень сведений, составляющих государственную тайну, определяется федеральным законом.
Статья 29.п4. Конституция РФ.

kats

  • Гость
Re: CBuilder
« Ответ #6 : 11-01-2005, 00:00:00 »
За код большое спасибо. Теперь знаю несколько способов как подсчитать время:), осталось только поставить задержку. Можно конечно сделать пустой цикл, но, по-моему, это несовсем красиво. Есть ещё так называемые таймеры, но синтаксис к этой функции никак ненайду:(
PS: плохо без хорошей книжки...

Devar

  • Гость
Re: CBuilder
« Ответ #7 : 11-01-2005, 00:00:00 »
Цитировать
PS: плохо без хорошей книжки...

А что в инете нет в электронном виде?
Или нет каких нибудь статей на эту тему?

kats

  • Гость
Re: CBuilder
« Ответ #8 : 11-01-2005, 00:00:00 »
Цитировать

А что в инете нет в электронном виде?
Или нет каких нибудь статей на эту тему?

Нашёл бы не спрашивал.
Но проблема решена:)  Lucefer, спасибо за помощь.

Devar

  • Гость
Re: CBuilder
« Ответ #9 : 11-01-2005, 00:00:00 »
Цитировать

Нашёл бы не спрашивал.
Но проблема решена:)  Lucefer, спасибо за помощь.

а зачем тебе ваще эта прога нужна?

Оффлайн Lucefer

  • Старожил
  • *****
  • Сообщений: 1947
  • Карма: +80/-16
  • Гитлер капут!
Re: CBuilder
« Ответ #10 : 12-01-2005, 00:00:00 »
Для обеспечения задержки есть такая команда Sleep и SleepEx
---
Sleep

The Sleep function suspends the execution of the current thread for at least the specified interval.

To enter an alertable wait state, use the SleepEx function.


void Sleep(
 DWORD dwMilliseconds
);

Parameters
dwMilliseconds
[in] Minimum time interval for which execution is to be suspended, in milliseconds.
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution.

A value of INFINITE indicates that the suspension should not time out.



The SleepEx function suspends the current thread until one of the following occurs:

An I/O completion callback function is called
An asynchronous procedure call (APC) is queued to the thread.
The minimum time-out interval elapses

DWORD SleepEx(
 DWORD dwMilliseconds,
 BOOL bAlertable
);

Parameters
dwMilliseconds
[in] Minimum time interval for which execution is to be suspended, in milliseconds.
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution.

A value of INFINITE indicates that the suspension should not time out.

bAlertable
[in] If this parameter is FALSE, the function does not return until the time-out period has elapsed. If an I/O completion callback occurs, the function does not return and the I/O completion function is not executed. If an APC is queued to the thread, the function does not return and the APC function is not executed.
If the parameter is TRUE and the thread that called this function is the same thread that called the extended I/O function ( ReadFileEx or WriteFileEx), the function returns when either the time-out period has elapsed or when an I/O completion callback function occurs. If an I/O completion callback occurs, the I/O completion function is called. If an APC is queued to the thread ( QueueUserAPC), the function returns when either the timer-out period has elapsed or when the APC function is called.

Return Values
The return value is zero if the specified time interval expired.

The return value is WAIT_IO_COMPLETION if the function returned due to one or more I/O completion callback functions. This can happen only if bAlertable is TRUE, and if the thread that called the SleepEx function is the same thread that called the extended I/O function.


Каждый имеет право свободно искать, получать, передавать, производить и распространять информацию любым законным способом. Перечень сведений, составляющих государственную тайну, определяется федеральным законом.
Статья 29.п4. Конституция РФ.

Devar

  • Гость
Re: CBuilder
« Ответ #11 : 12-01-2005, 00:00:00 »
-как же сдесь разобраться? Сдесь же все не по нашему написано.
- Запомни, в английском языке мата нет

NIHTRIK

  • Гость
Re: CBuilder
« Ответ #12 : 12-01-2005, 00:00:00 »
10 INPUT A
20 LET B = A + 1
30 PRINT B
40 END

kats

  • Гость
Re: CBuilder
« Ответ #13 : 12-01-2005, 00:00:00 »
Цитировать
10 INPUT A
20 LET B = A + 1
30 PRINT B
40 END

да ты.......программист:)
...да, весёлый язык программирования:)

NIHTRIK

  • Гость
Re: CBuilder
« Ответ #14 : 12-01-2005, 00:00:00 »
Цитировать

да ты.......программист:)
...да, весёлый язык программирования:)

Басик рулит !!!!!!!!