`time now` C++ Examples

27 C++ code examples are found related to "time now". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: timing.cc    From anyRTC-RTMP-OpenSource with GNU General Public License v3.0 6 votes vote down vote up
double Timing::WallTimeNow() {
#if defined(WEBRTC_POSIX)
  struct timeval time;
  gettimeofday(&time, NULL);
  // Convert from second (1.0) and microsecond (1e-6).
  return (static_cast<double>(time.tv_sec) +
          static_cast<double>(time.tv_usec) * 1.0e-6);

#elif defined(WEBRTC_WIN)
  struct _timeb time;
  _ftime(&time);
  // Convert from second (1.0) and milliseconds (1e-3).
  return (static_cast<double>(time.time) +
          static_cast<double>(time.millitm) * 1.0e-3);
#endif
} 
Example 2
Source File: misc.cpp    From janus with GNU General Public License v3.0 6 votes vote down vote up
void time_now_str(char* now) {
    time_t seconds_since_epoch = time(nullptr);
    struct tm local_calendar;
    localtime_r(&seconds_since_epoch, &local_calendar);
    make_int(now, local_calendar.tm_year + 1900, 4);
    now[4] = '-';
    make_int(now + 5, local_calendar.tm_mon + 1, 2);
    now[7] = '-';
    make_int(now + 8, local_calendar.tm_mday, 2);
    now[10] = ' ';
    make_int(now + 11, local_calendar.tm_hour, 2);
    now[13] = ':';
    make_int(now + 14, local_calendar.tm_min, 2);
    now[16] = ':';
    make_int(now + 17, local_calendar.tm_sec, 2);
    now[19] = '.';
    timeval tv;
    gettimeofday(&tv, nullptr);
    make_int(now + 20, tv.tv_usec / 1000, 3);
    now[23] = '\0';
} 
Example 3
Source File: profiler.cc    From oppai with GNU General Public License v3.0 5 votes vote down vote up
internalfn
f64 time_now()
{
    struct timespec t;

    memset(&t, 0, sizeof(struct timespec));

    if (clock_gettime(CLOCK_MONOTONIC, &t) < 0) {
        perror(0);
        exit(1);
    }

    return t.tv_sec + t.tv_nsec * (f64)1e-9;
} 
Example 4
Source File: simulator_test.cpp    From iroha with Apache License 2.0 5 votes vote down vote up
auto makeTx(size_t created_time = iroha::time::now()) {
  return shared_model::proto::TransactionBuilder()
      .createdTime(created_time)
      .creatorAccountId("admin@ru")
      .addAssetQuantity("coin#coin", "1.0")
      .quorum(1)
      .build()
      .signAndAddSignature(
          shared_model::crypto::DefaultCryptoAlgorithmType::generateKeypair())
      .finish();
} 
Example 5
Source File: Timer.cpp    From eomaia with MIT License 5 votes vote down vote up
string Timer::getNowTimeDate()
{
    time_t timep;
    struct tm *p;
    time(&timep);
    p = localtime(&timep);
    stringstream stream;
    stream<<(1900+p->tm_year)<<" "<<(1+p->tm_mon)<<"/"<<p->tm_mday<<" "<<p->tm_hour<<":"<<p->tm_min<<":"<<p->tm_sec<<endl;
    return stream.str();
} 
Example 6
Source File: Timer.cpp    From eomaia with MIT License 5 votes vote down vote up
uint64_t Timer::getNowTimeMSecond()
{
    struct  timezone   tz;
    struct timeval nowDate;
    gettimeofday(&nowDate,&tz);
    uint64_t ms = (nowDate.tv_sec)*1000+  nowDate.tv_usec/1000;
    return ms;
} 
Example 7
Source File: timetools.cc    From reindexer with Apache License 2.0 5 votes vote down vote up
int64_t getTimeNow(string_view mode) {
	auto tm = system_clock::now();
	auto duration = tm.time_since_epoch();

	if (iequals(mode, "sec"_sv)) {
		auto cnt = duration_cast<seconds>(duration).count();
		return static_cast<int64_t>(cnt);
	} else if 
Example 8
Source File: util_win.cc    From desktop-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
uint64_t GetTimeNow() {
  if (!qi_freq_.HighPart && !qi_freq_.LowPart) {
    QueryPerformanceFrequency(&qi_freq_);
  }
  LARGE_INTEGER t = {};
  QueryPerformanceCounter(&t);
  return static_cast<uint64_t>((t.QuadPart / double(qi_freq_.QuadPart)) *
                               1000000);
} 
Example 9
Source File: speed.cc    From wallet-android with GNU General Public License v2.0 5 votes vote down vote up
static uint64_t time_now() {
  struct timeval tv;
  uint64_t ret;

  gettimeofday(&tv, NULL);
  ret = tv.tv_sec;
  ret *= 1000000;
  ret += tv.tv_usec;
  return ret;
} 
Example 10
Source File: util.cpp    From cef-mixer with MIT License 5 votes vote down vote up
uint64_t time_now()
{
	if (!qi_freq_.HighPart && !qi_freq_.LowPart) {
		QueryPerformanceFrequency(&qi_freq_);
	}
	LARGE_INTEGER t = {};
	QueryPerformanceCounter(&t);
	return static_cast<uint64_t>(
		(t.QuadPart / double(qi_freq_.QuadPart)) * 1000000);
} 
Example 11
Source File: ad_conversions_unittest.cc    From brave-core with Mozilla Public License 2.0 5 votes vote down vote up
void TriggerAdEvent(
      const std::string& creative_set_id,
      const ConfirmationType confirmation_type,
      const base::Time time = base::Time::Now()) {
    AdHistory history;

    history.ad_content.creative_instance_id =
        "7a3b6d9f-d0b7-4da6-8988-8d5b8938c94f";
    history.ad_content.creative_set_id = creative_set_id;
    history.ad_content.ad_action = confirmation_type;
    history.timestamp_in_seconds = time.ToDoubleT();

    ads_->get_client()->AppendAdHistoryToAdsHistory(history);
  } 
Example 12
Source File: WheelTime.cpp    From duckdb with MIT License 5 votes vote down vote up
void CWheelTime::Set(CDateTime &Base, CDateTime &Now) {
	INT32 offset; // offset from BaseTime in milliseconds

	// DJ - If Now < Base, then we should probably throw an exception

	offset = Now.DiffInMilliSeconds(Base) / m_pWheelConfig->WheelResolution; // convert based on wheel resolution
	m_Cycles = offset / m_pWheelConfig->WheelSize;
	m_Index = offset % m_pWheelConfig->WheelSize;
} 
Example 13
Source File: WheelTime.cpp    From duckdb with MIT License 5 votes vote down vote up
void CWheelTime::Set(CDateTime *pBase, CDateTime *pNow) {
	INT32 offset; // offset from BaseTime in milliseconds

	// DJ - If Now < Base, then we should probably throw an exception

	offset = pNow->DiffInMilliSeconds(pBase) / m_pWheelConfig->WheelResolution; // convert based on wheel resolution
	m_Cycles = offset / m_pWheelConfig->WheelSize;
	m_Index = offset % m_pWheelConfig->WheelSize;
} 
Example 14
Source File: logger.cc    From Rainbomizer with GNU General Public License v3.0 5 votes vote down vote up
std::string
GetTimeNow ()
{
    time_t currentTime;
    char   str[256];

    time (&currentTime);

    auto tm = std::localtime (&currentTime);
    sprintf (str, "%02d-%02d-%04d", tm->tm_mday, tm->tm_mon + 1,
             1900 + tm->tm_year);

    return str;
} 
Example 15
Source File: PlayFabTestContext.cpp    From UnrealMarketplacePlugin with Apache License 2.0 5 votes vote down vote up
FString UPlayFabTestContext::GenerateTestSummary(FDateTime InNow)
{
    FString temp;
    temp = FString::FromInt(GetDurationInMilliseconds());
    while (temp.Len() < 12)
        temp = " " + temp;
    temp += " ms, ";
    switch (finishState)
    {
    case PlayFabApiTestFinishState::PASSED: temp += "pass: ";
        break;
    case PlayFabApiTestFinishState::FAILED: temp += "FAILED: ";
        break;
    case PlayFabApiTestFinishState::SKIPPED: temp += "SKIPPED: ";
        break;
    case PlayFabApiTestFinishState::TIMEDOUT: temp += "TIMED OUT: ";
        break;
    }
    temp += testName;
    if (testResultMsg.Len() > 0)
    {
        temp += " - ";
        temp += testResultMsg;
    }
    return temp;
} 
Example 16
Source File: aimd_rate_control.cc    From WebRTC-APM-for-Android with Apache License 2.0 5 votes vote down vote up
bool AimdRateControl::TimeToReduceFurther(int64_t time_now,
                                          uint32_t incoming_bitrate_bps) const {
  const int64_t bitrate_reduction_interval =
      std::max<int64_t>(std::min<int64_t>(rtt_, 200), 10);
  if (time_now - time_last_bitrate_change_ >= bitrate_reduction_interval) {
    return true;
  }
  if (ValidEstimate()) {
    const int threshold = static_cast<int>(kWithinIncomingBitrateHysteresis *
                                           incoming_bitrate_bps);
    const int bitrate_difference = LatestEstimate() - incoming_bitrate_bps;
    return bitrate_difference > threshold;
  }
  return false;
} 
Example 17
Source File: process_thread_impl.cc    From WebRTC-APM-for-Android with Apache License 2.0 5 votes vote down vote up
int64_t GetNextCallbackTime(Module* module, int64_t time_now) {
  int64_t interval = module->TimeUntilNextProcess();
  if (interval < 0) {
    // Falling behind, we should call the callback now.
    return time_now;
  }
  return time_now + interval;
} 
Example 18
Source File: timers.cpp    From foo_mediacontrol with BSD 2-Clause "Simplified" License 5 votes vote down vote up
uint64_t fileTimeNow() {
#ifdef _WIN32
		uint64_t ret;
		GetSystemTimeAsFileTime((FILETIME*)&ret);
		return ret;
#else
		return fileTimeUtoW(time(NULL));
#endif
	} 
Example 19
Source File: timeoutpublisherservice.cpp    From detectorgraph with Apache License 2.0 5 votes vote down vote up
void TimeoutPublisherService::ScheduleTimeoutDispatcher(
    DispatcherInterface* aDispatcher,
    const TimeOffset aMillisecondsFromNow,
    const TimeoutPublisherHandle aHandle)
{
    // Assert valid Handle
    DG_ASSERT(0 <= aHandle && (unsigned)aHandle < mTimeoutDispatchers.size());
    unsigned dispatcherIdx = (unsigned)aHandle;
    // Assert dispatcher is available
    DG_ASSERT(mTimeoutDispatchers[dispatcherIdx] == NULL);
    mTimeoutDispatchers[dispatcherIdx] = aDispatcher;
    SetTimeout(aMillisecondsFromNow, aHandle);
    Start(aHandle);
} 
Example 20
Source File: cpu_load_experiment.cpp    From derecho with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
void cpuNow(pthread_t t, struct timespec start_time) {
    struct timespec ts;
    clockid_t cid;

    pthread_getcpuclockid(t, &cid);
    clock_gettime(cid, &ts);
    // printf("%4ld.%03ld\n", ts.tv_sec, ts.tv_nsec / 1000000);
    double my_time = ts.tv_sec + ts.tv_nsec / 1e9;
    struct timespec end_time;
    clock_gettime(CLOCK_REALTIME, &end_time);
    double total_time = ((end_time.tv_sec * 1e9 + end_time.tv_nsec) - (start_time.tv_sec * 1e9 + start_time.tv_nsec)) / 1e9;

    cout << "CPU utilization: " << (my_time * 100) / total_time << "%" << endl;
} 
Example 21
Source File: speed_2_test.cpp    From apollo_ros_bridge with Apache License 2.0 5 votes vote down vote up
uint64_t now_time() {
  high_resolution_clock::time_point now = high_resolution_clock::now();
  auto nano_now = std::chrono::time_point_cast<std::chrono::nanoseconds>(now);
  auto epoch = nano_now.time_since_epoch();
  uint64_t nano_time =
      std::chrono::duration_cast<std::chrono::nanoseconds>(epoch).count();
  return nano_time;
} 
Example 22
Source File: platform.c    From awtk with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ret_t date_time_set_now_impl(date_time_t* dt) {
  struct tm tms;
  time_t t = 0;
  memset(&tms, 0x00, sizeof(tms));

  tms.tm_year = dt->year - 1900;
  tms.tm_mon = dt->month - 1;
  tms.tm_mday = dt->day;
  tms.tm_hour = dt->hour;
  tms.tm_min = dt->minute;
  tms.tm_sec = dt->second;

  t = mktime(&tms);
#ifdef LINUX
  {
    struct timeval tv;
    tv.tv_sec = t;
    tv.tv_usec = 0;
    if (settimeofday(&tv, (struct timezone*)0) < 0) {
      perror("stime failed\n");
      return RET_FAIL;
    }
  }
#endif /*LINUX*/

  return RET_OK;
} 
Example 23
Source File: platform.c    From awtk with GNU Lesser General Public License v2.1 5 votes vote down vote up
static ret_t date_time_get_now_impl(date_time_t* dt) {
  SYSTEMTIME wtm;
  GetLocalTime(&wtm);

  dt->second = wtm.wSecond;
  dt->minute = wtm.wMinute;
  dt->hour = wtm.wHour;
  dt->day = wtm.wDay;
  dt->wday = wtm.wDayOfWeek;
  dt->month = wtm.wMonth;
  dt->year = wtm.wYear;

  return RET_OK;
} 
Example 24
Source File: TimerQueue.cc    From fastcgi-async-or-coroutine with MIT License 5 votes vote down vote up
struct timespec howMuchTimeFromNow(Timestamp when)
{
  int64_t microseconds = when.microSecondsSinceEpoch()
                         - Timestamp::now().microSecondsSinceEpoch();
  if (microseconds < 100)
  {
    microseconds = 100;
  }
  struct timespec ts;
  ts.tv_sec = static_cast<time_t>(
      microseconds / Timestamp::kMicroSecondsPerSecond);
  ts.tv_nsec = static_cast<long>(
      (microseconds % Timestamp::kMicroSecondsPerSecond) * 1000);
  return ts;
} 
Example 25
Source File: opentracing.cc    From kv_engine with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
void OpenTracingThread::pushOne(
        std::chrono::system_clock::time_point system_now,
        std::chrono::steady_clock::time_point steady_now,
        const CookieTraceContext& entry) {
#ifdef ENABLE_OPENTRACING
    try {
        ParentSpan parent;

        if (entry.context.find('=') == std::string::npos) {
            // this is most likely a binary encoded blob
            parent = decodeAsBinary(entry.context);
            if (!parent) {
                // fall back to text:
                parent = decodeAsTextMap(entry.context);
            }
        } else {
            // this is most likely a text-map
            parent = decodeAsTextMap(entry.context);
            if (!parent) {
                // fall back to binary blob
                parent = decodeAsBinary(entry.context);
            }
        }

        if (!parent) {
            LOG_WARNING("Failed to parse OpenTracing context");
            return;
        }

        for (const auto& d : entry.traceSpans) {
            // Convert the start time to our system clock
            const auto start =
                    system_now - std::chrono::duration_cast<
                                         std::chrono::system_clock::duration>(
                                         steady_now - d.start);

            std::string text;
            if (d.code == cb::tracing::Code::Request) {
                if (cb::mcbp::is_client_magic(entry.magic)) {
                    text = to_string(cb::mcbp::ClientOpcode(entry.opcode));
                } else {
                    text = to_string(cb::mcbp::ServerOpcode(entry.opcode));
                }
            } else { 
Example 26
Source File: monotonic_clock.cc    From mediapipe with Apache License 2.0 4 votes vote down vote up
virtual absl::Time TimeNow() {
    // These variables save some state from the critical section below.
    absl::Time raw_time;
    absl::Time local_max_time;
    absl::Time local_last_raw_time;

    // As there are several early exits from this function, use absl::MutexLock.
    {
      absl::MutexLock m(&state_->lock);

      // Check consistency of internal data with state_.
      CHECK_LE(last_raw_time_, state_->max_time)
          << "non-monotonic behavior: last_raw_time_=" << last_raw_time_
          << ", max_time=" << state_->max_time;

      raw_time = state_->raw_clock->TimeNow();

      // Normal case: time is advancing.  Update state and return the raw time.
      if (raw_time >= state_->max_time) {
        last_raw_time_ = raw_time;
        state_->max_time = raw_time;
        return raw_time;
      }

      // Exceptional case: Raw time is within a window of a previous backward
      // jump.  We do not run any callbacks or update metrics here since we
      // already did that when the backward jump was detected.
      if (raw_time >= last_raw_time_) {
        last_raw_time_ = raw_time;
        return state_->max_time;
      }

      // Exceptional case: Raw time jumped backward.  Remainder of function
      // handles this case.
      //
      // First, update correction metrics.
      ++correction_count_;
      absl::Duration delta = state_->max_time - raw_time;
      CHECK_LT(absl::ZeroDuration(), delta);
      if (delta > max_correction_) {
        max_correction_ = delta;
      }

      // Copy state into local vars before updating last_raw_time_ and leaving
      // the critical section.
      local_max_time = state_->max_time;
      local_last_raw_time = last_raw_time_;
      last_raw_time_ = raw_time;
    }  // absl::MutexLock

    // Return the saved maximum time.
    return local_max_time;
  }